模拟 localStorage 时如何实现过期时间功能

在前端模拟 localStorage 并实现过期时间功能,主要思路是将过期时间与存储的数据一起保存,并在读取数据时检查是否过期。以下提供两种实现方式:

方法一:利用 JSON.stringifyJSON.parse

这种方法将数据和过期时间一起存储在一个 JSON 字符串中。

const myLocalStorage = {
  setItem(key, value, expirationTime) { // expirationTime in milliseconds
    const now = new Date().getTime();
    const item = {
      value: value,
      expiry: now + expirationTime,
    };
    localStorage.setItem(key, JSON.stringify(item));
  },

  getItem(key) {
    const itemStr = localStorage.getItem(key);
    if (!itemStr) {
      return null;
    }
    const item = JSON.parse(itemStr);
    const now = new Date().getTime();
    if (now > item.expiry) {
      localStorage.removeItem(key);
      return null;
    }
    return item.value;
  },

  removeItem(key) {
    localStorage.removeItem(key);
  },

  clear() {
    localStorage.clear();
  }
};


// 使用示例:
myLocalStorage.setItem('name', 'Gemini', 10000); // 10 秒后过期
console.log(myLocalStorage.getItem('name')); // 输出: Gemini

setTimeout(() => {
  console.log(myLocalStorage.getItem('name')); // 10 秒后,输出: null
}, 10000);


myLocalStorage.setItem('age', 2, 5000); // 5 秒后过期
console.log(myLocalStorage.getItem('age')); // 输出:2

myLocalStorage.removeItem('age');
console.log(myLocalStorage.getItem('age')); // 输出:null

方法二:分别存储数据和过期时间

这种方法将数据和过期时间分别存储在 localStorage 中,使用相同的 key 但添加后缀区分。

const myLocalStorage = {
  setItem(key, value, expirationTime) {
    localStorage.setItem(key, value);
    localStorage.setItem(`${key}_expiry`, new Date().getTime() + expirationTime);
  },

  getItem(key) {
    const expiry = localStorage.getItem(`${key}_expiry`);
    if (!expiry || new Date().getTime() > expiry) {
      localStorage.removeItem(key);
      localStorage.removeItem(`${key}_expiry`);
      return null;
    }
    return localStorage.getItem(key);
  },

  removeItem(key) {
    localStorage.removeItem(key);
    localStorage.removeItem(`${key}_expiry`);
  },

  clear() {
    localStorage.clear();
  }
};

// 使用示例:
myLocalStorage.setItem('name', 'Gemini', 10000); // 10 秒后过期
console.log(myLocalStorage.getItem('name')); // 输出: Gemini

setTimeout(() => {
  console.log(myLocalStorage.getItem('name')); // 10 秒后,输出: null
}, 10000);

两种方法的比较:

  • 方法一 更简洁,将数据和过期时间存储在一起,更易于管理。
  • 方法二 需要存储两条数据,占用略多的存储空间,但读取速度可能会略快一些,因为不需要 JSON.parse 操作。

选择哪种方法取决于具体需求和偏好。 两种方法都实现了带有过期时间的 localStorage 模拟。 记住,这只是模拟 localStorage 的行为,实际存储仍然依赖于浏览器原生的 localStorage

希望以上信息对您有所帮助!

posted @   王铁柱6  阅读(32)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示