Skip to content

Instantly share code, notes, and snippets.

@toddway
Created April 29, 2013 21:43
Show Gist options
  • Save toddway/5485056 to your computer and use it in GitHub Desktop.
Save toddway/5485056 to your computer and use it in GitHub Desktop.
Cache getJSON calls
var fetchCache = {};
function fetchJSON(url, callback, secondsToCache) {
secondsToCache = secondsToCache ? secondsToCache : 60*60; //default to one hour
var nowInSeconds = Math.round(new Date().getTime() / 1000);
if (!fetchCache[url] || ((fetchCache[url].timestamp + secondsToCache) < nowInSeconds)) {
$.getJSON(url, function(response) {
fetchCache[url] = {response: response, timestamp: nowInSeconds};
callback(fetchCache[url].response);
});
}
else {
callback(fetchCache[url].response);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment