LocalStorage带时间戳自动过期缓存的核心是写入时存时间戳与数据对象,读取时用Date.now()校验是否超期,超期则清除并返回null;需处理解析异常、配额超限及系统时间篡改等边界情况。

在 LocalStorage 中实现带时间戳的自动过期缓存,核心思路是:每次写入时附加当前时间戳,读取时对比时间戳与预设有效期,过期则清除并返回 null。
存储时添加时间戳和原始数据
把需要缓存的数据和生成时间一起打包成对象,再序列化存入 LocalStorage。注意不要直接覆盖原值,而是结构化保存。
- 用 Date.now() 获取毫秒级时间戳(比 new Date() 更简洁、无时区干扰)
- 有效期建议以毫秒为单位(如 5 分钟 = 5 * 60 * 1000),便于计算
- 示例写法:
function setCache(key, value, expiresMs = 5 * 60 * 1000) {
const item = {
data: value,
timestamp: Date.now(),
expires: expiresMs
};
localStorage.setItem(key, JSON.stringify(item));
}读取时校验是否过期
读取后先解析,再判断当前时间是否超过“写入时间 + 有效期”,超时就主动删除并返回 null,避免后续误用过期数据。
你接手一个需求时,是不是经常这样:"改一个小字段 → 结果把不相关的代码也改了"、"需求说得很模糊 → 做着做着发现跑偏了"、"数据库加个字段 → 上线才发现漏了数据兼容"、"做了个新功能 → 一个月后自己都忘了当时怎么设计的"、"写到一半被中断 → 再回来不知道从哪继续";这个 Skill 就是专门解决这些问题的。 它会自动探测你的项目环境(JDK、Spring Boot、ORM、数据库、前端框架),记在
- 用 Date.now() - item.timestamp >= item.expires 判断过期
- 过期后调用 localStorage.removeItem(key) 清理,保持存储干净
- 未过期才返回 item.data,不返回整个缓存对象
function getCache(key) {
const itemStr = localStorage.getItem(key);
if (!itemStr) return null;
<p>const item = JSON.parse(itemStr);
if (Date.now() - item.timestamp >= item.expires) {
localStorage.removeItem(key);
return null;
}</p><p>return item.data;
}封装成可复用的工具函数
把 set/get 逻辑合并,并支持自定义默认过期时间,减少重复判断。也可扩展支持「永久缓存」(expires 设为 0 或 null)。
立即学习“Java免费学习笔记(深入)”;
- 设置默认过期时间为 10 分钟(可按需调整)
- 允许传入 null 或 0 表示不过期
- 读取失败(JSON 解析异常)时也应安全降级,返回 null 而非抛错
const Cache = {
set(key, value, expiresMs = 10 * 60 * 1000) {
if (expiresMs > 0) {
const item = { data: value, timestamp: Date.now(), expires: expiresMs };
try {
localStorage.setItem(key, JSON.stringify(item));
} catch (e) {
// QuotaExceededError 等忽略
}
} else {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch (e) {}
}
},
<p>get(key) {
const itemStr = localStorage.getItem(key);
if (!itemStr) return null;</p><pre class='brush:php;toolbar:false;'>try {
const item = JSON.parse(itemStr);
// 判断是否含 timestamp 字段来区分「带过期」和「永久缓存」
if (typeof item.timestamp === 'number' && typeof item.expires === 'number' && item.expires > 0) {
if (Date.now() - item.timestamp >= item.expires) {
localStorage.removeItem(key);
return null;
}
return item.data;
}
return item; // 永久缓存,直接返回
} catch (e) {
localStorage.removeItem(key); // 解析失败,清理脏数据
return null;
}} };
注意浏览器限制和边界情况
LocalStorage 是同步 API,容量有限(通常 5–10MB),且所有数据均为字符串。实际使用中需防范几类问题:
- 存储失败:超出配额时 setItem 会抛出 QuotaExceededError,建议用 try/catch 包裹
- 时间不可靠:用户手动修改系统时间会导致过期判断失准,对安全性要求高的场景不宜依赖本地时间
- 跨标签页不同步:LocalStorage 不触发跨窗口事件(如 storage 事件可监听,但延迟存在),需配合其他机制做协同
- 敏感数据勿存:LocalStorage 可被 XSS 直接读取,绝不存储 token、密码等

















