Skip to content

Instantly share code, notes, and snippets.

@westc
Last active August 29, 2015 14:09
Show Gist options
  • Save westc/2a04d7d6399c20c9f7c5 to your computer and use it in GitHub Desktop.
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.
/**
* 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