Skip to content

Instantly share code, notes, and snippets.

@robhudson
Last active December 14, 2015 16:09
Show Gist options
  • Save robhudson/5112940 to your computer and use it in GitHub Desktop.
Save robhudson/5112940 to your computer and use it in GitHub Desktop.
caching and localStorage
var lsCache = function() {
var TIMEOUT_DEFAULT = 60;
var self = {
set: function(key, val, timeout) {
var timeout = parseInt(timeout, 10) || TIMEOUT_DEFAULT;
var now = Math.round(new Date().getTime() / 1000);
localStorage.setItem(key, val);
localStorage.setItem(key + '.timeout', now * timeout);
},
get: function(key) {
var timeout = localStorage.getItem(key + '.timeout');
var now = Math.round(new Date().getTime() / 1000);
if (timeout && timeout < now) {
localStorage.removeItem(key);
localStorage.removeItem(key + '.timeout');
}
return localStorage.getItem(key);
}
};
return self;
};
var testVal = lsCache().set('key', 'value', 1);
console.log('has key');
console.log(lsCache().get('key'));
setTimeout(function() {
console.log('no key');
console.log(lsCache().get('key'));
}, 1500);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment