【study】清除localStorage超过一个小时的数据

74 阅读1分钟
  1. 清除过期数据:在清除数据时检查存储的时间戳,删除超过一个小时的数据。
  2. 定义一个辅助函数,用于将数据存储到 localStorage 并附带当前的时间戳
function setItemWithTimestamp(key, value) {
  const item = {
    value: value,
    timestamp: new Date().getTime()
  };
  localStorage.setItem(key, JSON.stringify(item));
}
  1. 清除一个小时之前的数据
function clearOldData() {
  const now = new Date().getTime();
  const oneHour = 60 * 60 * 1000; // 一小时的毫秒数
  
  for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i);
    const item = JSON.parse(localStorage.getItem(key));
    
    if (item && item.timestamp && now - item.timestamp > oneHour) {
      localStorage.removeItem(key);
    }
  }
}