Skip to content

Instantly share code, notes, and snippets.

@ryasmi
Last active August 29, 2015 14:24
Show Gist options
  • Save ryasmi/d640c23d0a1ba2331850 to your computer and use it in GitHub Desktop.
Save ryasmi/d640c23d0a1ba2331850 to your computer and use it in GitHub Desktop.
A function to memoize and throttle a functions result.
var cache = function (callback, initialValue, wait) {
var cachedArgs = [];
var cachedResults = [];
var cachedWait = [];
initialValue = initialValue || function () {
return undefined;
};
return function () {
var args = [].slice.call(arguments, 0);
var jsonArgs = JSON.stringify(args);
var cacheIndex = cachedArgs.indexOf(jsonArgs);
if (cacheIndex === -1) {
cacheIndex = cachedArgs.length;
cachedArgs.push(jsonArgs);
cachedResults[cacheIndex] = initialValue();
cachedWait[cacheIndex] = false
}
if (cachedWait[cacheIndex] === false) {
setTimeout(function () {
cachedResults[cacheIndex] = callback.apply(null, [cachedResults[cacheIndex]].concat(args));
setTimeout(function () {
cachedWait[cacheIndex] = false;
}, wait || 0);
});
cachedWait[cacheIndex] = true;
} else {
console.info('Not re-running throttled function.');
}
return cachedResults[cacheIndex];
};
};
var add = cache(function (cache, x, y) {
console.log('Trigger an event to refresh app?');
return x + y;
}, function () {
return undefined;
}, 2000);
add(10, 11); // Returns undefined until cached function returns.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment