We all know that localStorage is not actively deleted and will never be destroyed, so how to set the expiration time of localStorage? Let’s try it together today!
<script type=text/javascript> //Encapsulate expiration control code function set(key,value){ var curTime = new Date().getTime(); localStorage.setItem(key,JSON.stringify({data:value,time :curTime})); } function get(key,exp){ var data = localStorage.getItem(key); var dataObj = JSON.parse(data); if (new Date().getTime() - dataObj.time>exp) { console.log('Information has expired'); //alert(information has expired) }else{ //console.log(data=+dataObj.data) ; //console.log(JSON.parse(dataObj.data)); var dataObjDatatoJson = JSON.parse(dataObj.data) return dataObjDatatoJson; } } </script>
Usage scenarios:
1. Use local data to reduce network transmission
2. In a weak network environment, high latency, low bandwidth, try to localize the data
How to use:
<script>window.onload = function(){ var Ipt = document.getElementById('input1'); var value = '{name:Hepai Kongming,Age:18,address:Lujiazui Financial City}'; set('information ',value); Ipt.onclick = function(){ //var dataObjData=get('information',1000);//The expiration time is 1 second. Under normal circumstances, it has expired when you click it//var dataObjData=get('information',1000*60);//The expiration time is 1 minute//var dataObjData=get('information',1000*60*60);//Expiration time is 1 hour//var Obj=get('information',1000*60*60*24);//The expiration time is 24 hours var dataObjData=get('information',1000*60*60*24*7);//The expiration time is 1 Zhou console.log(dataObjData || null); if (dataObjData!= && dataObjData!=null) { console.log(Name:+dataObjData.name); console.log(Age:+dataObjData.Age); console.log(Address:+dataObjData.Age); }else{ alert(The information obtained has expired); } } }</script>localStorage expiration control running code results are not expired LocalStorage expiration control results of running code have expired
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.