Skip to content

Instantly share code, notes, and snippets.

@dtao
Created May 17, 2012 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dtao/2721333 to your computer and use it in GitHub Desktop.
Save dtao/2721333 to your computer and use it in GitHub Desktop.
Function to throttle a callback so that it only executes after a specified amount of time has elapsed since the last invocation
function throttle(callback, delay, before) {
var busy = false;
var hold = false;
function callAfterDelay(self, args) {
setTimeout(function() {
if (hold) {
hold = false;
callAfterDelay(self, args);
return;
}
try {
callback.apply(self, args);
} finally {
busy = false;
}
}, delay);
}
return function() {
if (busy) {
hold = true;
return;
}
if (typeof before === "function") {
before.apply(this, arguments);
}
busy = true;
callAfterDelay(this, arguments);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment