如何使用Dexie.js的Timestamp删除指定时长后的IndexedDB缓存
解决方案:按时长删除Dexie.js缓存
嘿,这个需求其实很好实现,核心就是把你想要的缓存时长转换成毫秒数,然后用当前时间减去这个毫秒值,得到「缓存过期的时间阈值」——所有timestamp小于这个阈值的缓存都该被清理掉了。
第一步:理解时间戳的逻辑
你已经在保存缓存时用了new Date().getTime()(和Date.now()等价)记录timestamp,这一步是完全正确的:它返回从1970年至今的毫秒数,非常适合做时间差计算。
第二步:实现过期时间计算函数
我们可以写一个灵活的函数,根据你需要的时长(小时、分钟、秒)计算出过期的时间戳:
// 计算过期时间戳:传入需要保留的缓存时长,返回过期阈值 function getCacheExpiryTimestamp(options) { // 默认值:不传参数时默认保留1小时缓存 const { hours = 1, minutes = 0, seconds = 0 } = options || {}; // 把所有时长统一转换成毫秒数 const totalMilliseconds = (hours * 60 * 60 + minutes * 60 + seconds) * 1000; // 当前时间减去总毫秒数,得到过期的时间戳 return Date.now() - totalMilliseconds; }
第三步:调用Dexie删除过期缓存
现在你可以直接用这个函数来删除指定时长前的缓存,几个常用场景的示例如下:
示例1:删除1小时前的缓存
db.product.where("timestamp").below(getCacheExpiryTimestamp({ hours: 1 })).delete() .then(function (deleteCount) { console.log(`Deleted ${deleteCount} old cache entries`); }) .catch(function(error) { console.log(`Error deleting old cache: ${error}`); });
示例2:删除5分钟前的缓存
// 用分钟参数直接指定 db.product.where("timestamp").below(getCacheExpiryTimestamp({ minutes: 5 })).delete()
示例3:删除60小时前的缓存
db.product.where("timestamp").below(getCacheExpiryTimestamp({ hours: 60 })).delete()
额外小提示
- 如果你不再需要之前的
date字段,可以从保存缓存的代码里去掉,减少IndexedDB的存储空间占用; - 建议把清理缓存的逻辑放在合适的时机执行,比如页面加载完成后、用户操作间隙,避免影响页面性能。
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

