Last active
March 18, 2016 17:51
-
-
Save kindziora/d42c884ccb77dc0b5517 to your computer and use it in GitHub Desktop.
simple javascript caching using localStorage and a time to live (TTL)
This file contains 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 cache = function() { | |
var store = window.localStorage; | |
return { | |
set: function(key, value, ttl){ | |
var time = new Date(); | |
time.setTime(time.getTime() + ttl); | |
store.setItem(key, JSON.stringify({ | |
ttl: time.getTime(), | |
content: value | |
})); | |
}, | |
get: function(key){ | |
var data = store.getItem(key); | |
if (!data){ | |
return null; | |
} | |
var entry = JSON.parse(data); | |
var now = new Date().getTime(); | |
if( now > entry.ttl ){ | |
this.remove(key); | |
} | |
return entry; | |
}, | |
remove: function(key){ | |
store.removeItem(key); | |
}, | |
clear: function(){ | |
store.clear(); | |
} | |
}; | |
} | |
var layer = cache(); | |
layer.set("test1", {"hallo" : "lorem ipsum"}, 1000 * 10); | |
window.setInterval(function() { | |
console.log(layer.get("test1")); | |
}, 1000); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment