Created
May 17, 2012 20:17
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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