Skip to content

Instantly share code, notes, and snippets.

@codename065
Created February 3, 2018 10:18
Show Gist options
  • Select an option

  • Save codename065/ee93e4e31a1de8caa3c0329e41804f0d to your computer and use it in GitHub Desktop.

Select an option

Save codename065/ee93e4e31a1de8caa3c0329e41804f0d to your computer and use it in GitHub Desktop.
JavaScript local storage handler with expiration time
var tempStorage = {
get: function (name) {
var now = Math.floor(Date.now() / 1000);
var _lsd = localStorage.getItem(name);
if(_lsd == null) return null;
var obj = JSON.parse(_lsd);
if(obj.expire >= now){
return obj.data;
} else {
localStorage.removeItem(name);
return null;
}
},
set: function (name, value, expire = 3600) {
var now = Math.floor(Date.now() / 1000);
expire = now + expire;
var obj = {
data: value,
expire: expire
};
localStorage.setItem(name, JSON.stringify(obj));
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment