Skip to content

Instantly share code, notes, and snippets.

@josher19
Created December 21, 2011 08:58
Show Gist options
  • Save josher19/1505299 to your computer and use it in GitHub Desktop.
Save josher19/1505299 to your computer and use it in GitHub Desktop.
Caching in Javascript
cachedWorkerInfo = {
cacheTimeSecs: 60 /* 60 seconds == 1 minute */
, timeoutId : 0
, get: function (workerId, sql) { return this._checkCached(workerId, sql) && this[workerId]['sqlResults']}
, put: function (workerId, sql, sqlResults) { return this[workerId] = {'sql': sql, 'sqlResults': sqlResults, 'queryTime': new Date()}; }
, scheduleCleanup : function() { if (!cachedWorkerInfo.timeoutId) cachedWorkerInfo.timeoutId = setTimeout(cachedWorkerInfo.clear, cachedWorkerInfo.cacheTimeSecs * 2 * 1000); /* called maximum of once per 2 minutes */ }
, clear : function clear(everything) { var that=cachedWorkerInfo, now = new Date(); for (var x in that) {if (typeof that[x] != "function" && null != that[x] && null != that[x].queryTime) {if (true == everything || false == that._stillValid(x, now)) {delete that[x] ;}}} that.timeoutId = 0; }
, _checkCached: function (workerId,sql) { return this[workerId] != null && this[workerId]['sql'] === sql && this._stillValid(workerId, new Date()); }
, _stillValid: function (workerId, now) { return now - this[workerId]['queryTime'] < this.cacheTimeSecs * 1000; }
};
// Typical usage (you define doSqlQuery):
function get_cached_worker_id(workerId, sql, doSqlQuery, verbose) {
var results = cachedWorkerInfo.get(workerId, sql);
if (!results) {
results = doSqlQuery(sql);
cachedWorkerInfo.put(workerId, sql, results);
cachedWorkerInfo.scheduleCleanup(); /* delete old entries 2 minutes after first query */
}
if (verbose && results != cachedWorkerInfo.get(workerId, sql)) {
alert("Could not cache " + sql);
}
return results;
}
var result, workerId = 30, sql = "SELECT * from worker where worker_id = '30';", verbose=true;
if (!window.doSqlQuery) doSqlQuery = function(sql) { return sql; /* usually ajax request to MySQL */ }
result = get_cached_worker_id(workerId, sql, doSqlQuery, verbose);
alert(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment