每次在存储的时候同时也存入一个时效时间戳,而在获取数据前,先与当前时间比较,如果小于当前时间则过期了,直接返回空的数据。
<input type="button" value="存值" id="button1"/> <input type="button" value="取值" id="button2"/>
let a = '111'; let curData = Date.now(); let time = 1000*60+curData; document.getElementById("button1").onclick = function(){ window.localStorage['a'] = a; window.localStorage['a__expires__']=time; } document.getElementById("button2").onclick = function(){ let timeout = window.localStorage['a__expires__']; if(Date.now()>=time){ window.localStorage.removeItem('a');
window.localStorage.removeItem('a_expires_');
} console.log(window.localStorage['a']); }
参考至这里