Last active
December 14, 2015 16:09
-
-
Save robhudson/5112940 to your computer and use it in GitHub Desktop.
caching and localStorage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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