设置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);