localStorage 设置过期时间

设置localStorage过期时间方法。

/****
* name:localStorage的key
* data:localStorage的Value
* expire:localStorage的过期时间,默认是1天后过期
****/
//
设置缓存 const localStorageSet = (name, data, expire = new Date().getTime() + expire * 60 * 60 * 1000) => { const obj = { data, expire }; localStorage.setItem(name, JSON.stringify(obj)); }; //读取缓存 const localStorageGet = name => { const storage = localStorage.getItem(name); const time = new Date().getTime(); let result = {}; if (storage) { const obj = JSON.parse(storage); if (time < obj.expire) { result = obj.data; } else { localStorage.removeItem(name); } } return result; };

 

使用:

设置过期时间为第2天凌晨。

let expire = new Date(new Date().setDate(new Date().getDate() + 1)).setHours(0, 0, 0, 0);
localStorageSet('popup', {
    showOnce: true,
}, expire);
posted @ 2019-12-30 14:36  前端[色色]  阅读(5466)  评论(0编辑  收藏  举报