Skip to content

Instantly share code, notes, and snippets.

@justinobney
Last active August 29, 2015 14:09
Show Gist options
  • Save justinobney/651dbd0a6e07948d0f6f to your computer and use it in GitHub Desktop.
Save justinobney/651dbd0a6e07948d0f6f to your computer and use it in GitHub Desktop.
var cache = {};
function checkCache(key){
if(cache[key]){
return cache[key];
} else {
// do some long/expensive action
// ex: calculation, ajax, etc...
cache[key] = Math.random();
return cache[key];
}
}
// This will keep it in the cache unless
// it is older than 5 seconds
var cache = {};
function checkCache(key){
var now = +new Date();
var found = cache[key];
if(found && isNotOld(now, found.ts)){
return cache[key];
} else {
cache[key] = {
val: Math.random(),
ts: +new Date()
};
return cache[key];
}
}
function isNotOld(t1, t2){
var lifetime = 5000;
return Math.abs(t1-t2) < 5000
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment