Skip to content

Instantly share code, notes, and snippets.

@subtleGradient
Created May 7, 2009 00:53
Show Gist options
  • Select an option

  • Save subtleGradient/107849 to your computer and use it in GitHub Desktop.

Select an option

Save subtleGradient/107849 to your computer and use it in GitHub Desktop.
Function.prototype.remember = function remember(delay,maxConcurrentRuns){
maxConcurrentRuns = maxConcurrentRuns || 1;
var self = this, tim, result, block=0;
function resetBlock(){ block --; };
function rememberWrapper(){
if (block < maxConcurrentRuns) {
block ++;
result = self.apply(this,arguments);
if (delay) setTimeout(resetBlock, delay);
}
return result;
};
rememberWrapper.displayName = (this.displayName || this.name || '') + ' slowed';
return rememberWrapper;
};
// ========
// = TEST =
// ========
var a = 0;
function incrementA(){ a++; };
incrementA();
incrementA();
incrementA();
incrementA();
console.assert(a === 4, 'a should have incremented as many times as I ran the function since nothing is stopping us from running as many times as we want! muahaha!');
// ========
// = TEST =
// ========
a = 0;
var incrementA = incrementA.remember(10);
incrementA();
incrementA();
incrementA();
incrementA();
console.assert(a === 1, "a should have only incremented once");
// ========
// = TEST =
// ========
setTimeout(function(){
incrementA();
console.assert(a === 2, 'a should have incremented again since the delay to run again is up!');
incrementA();
console.assert(a === 2, 'a should not have incremented again since the delay is back!');
}, 100);
// ========
// = TEST =
// ========
b = 0;
var incrementB = function(){ b++; }.remember(10,2);
incrementB();
incrementB();
incrementB();
incrementB();
console.assert(b === 2, "a should have incremented twice since that's the max");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment