Last active
August 29, 2015 14:09
-
-
Save westc/2a04d7d6399c20c9f7c5 to your computer and use it in GitHub Desktop.
A way to rate limit function calls by queueing up the context and arguments to be called at a later time.
This file contains 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
/** | |
* Copies a function and rate limits it so it will only execute once within the | |
* given amount of milliseconds. | |
* @param {!Function} fn The function to be rate limited. | |
* @param {number} threshold The minimum amount of milliseconds between | |
* subsequent function executions. | |
* @param {boolean=} opt_waitAfter Optional parameter defaulting to false. | |
* If set to true the delay doesn't start until after the function | |
* executes. | |
* @return {!Function} The rate limited version of the function passed in. | |
*/ | |
function queue(fn, threshold, opt_waitAfter) { | |
var timeout, lastTime = 0, calls = []; | |
return function() { | |
caller(calls.push([this, arguments])); | |
}; | |
function caller() { | |
if (timeout == undefined) { | |
timeout = setTimeout(function() { | |
try { | |
var contextAndArgs = calls.shift(); | |
!opt_waitAfter && (lastTime = +new Date); | |
fn.apply(contextAndArgs[0], contextAndArgs[1]); | |
} | |
catch (e) { | |
throw e; | |
} | |
finally { | |
opt_waitAfter && (lastTime = +new Date); | |
timeout = undefined; | |
if (calls[0]) { | |
caller(); | |
} | |
} | |
}, Math.max(0, threshold - new Date + lastTime)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment