【JavaScript】原生 JavaScript 实现 localStorage 过期时间
一、核心实现原理
通过存储包含 数据值 + 时间戳 + 过期时间 的复合对象,利用时间差判断数据是否过期:
// 数据结构示例
{value: "实际数据", // 原始数据time: 1715568000000, // 存储时间戳(毫秒)expire: 86400000 // 过期时间(毫秒)
}
二、基础实现方法
- 函数封装法(推荐)
// 存储数据(支持秒/毫秒单位)
function setWithExpire(key, value, expire) {const now = Date.now();const data = {value: value,time: now,expire: typeof expire === 'number' ? expire * 1000 : expire // 兼容秒单位};localStorage.setItem(key, JSON.stringify(data));
}// 读取数据(自动清除过期项)
function getWithExpire(key) {const item = JSON.parse(localStorage.getItem(key));if (!item) return null;const isExpired = Date.now() - item.time > item.expire;if (isExpired) {localStorage.removeItem(key);return null;}return item.value;
}
调用示例:
setWithExpire('token', 'abc123', 3600); // 1小时后过期
setTimeout(() => getWithExpire('token'), 4000); // 4秒后获取
- 原型扩展法(增强原生API)
// 扩展Storage原型
Storage.prototype.setExpire = function(key, value, expire) {const data = { value: value, time: Date.now(), expire: expire };this.setItem(key, JSON.stringify(data));
};Storage.prototype.getExpire = function(key) {const item = JSON.parse(this.getItem(key));if (!item || Date.now() - item.time > item.expire) {this.removeItem(key);return null;}return item.value;
};// 调用方式
localStorage.setExpire('theme', 'dark', 86400000);
console.log(localStorage.getExpire('theme'));
三、进阶优化方案
- 启动时自动清理过期数据
function initStorageExpiration() {Object.keys(localStorage).forEach(key => {try { // 防止非本方案数据干扰const item = JSON.parse(localStorage.getItem(key));if (item?.expire && Date.now() - item.time > item.expire) {localStorage.removeItem(key);}} catch {}});
}
// 页面加载时执行
initStorageExpiration();
- 定时清理机制(可选)
// 每小时检查一次
setInterval(() => {Object.keys(localStorage).forEach(key => {getWithExpire(key); // 复用读取时的清理逻辑});
}, 3600000);