Last active
August 29, 2015 14:09
-
-
Save justinobney/651dbd0a6e07948d0f6f to your computer and use it in GitHub Desktop.
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 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 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
// 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