Skip to content

Instantly share code, notes, and snippets.

@atmin
Last active December 20, 2015 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atmin/6104869 to your computer and use it in GitHub Desktop.
Save atmin/6104869 to your computer and use it in GitHub Desktop.
Execute given `func`tion no more often than once every `delay` milliseconds, queue all calls, do not drop anything (unlike throttle and debounce)
/*
** Execute given `func`tion no more often than once every `delay` milliseconds,
** queue all calls, do not drop anything (unlike throttle and debounce)
**
** Example usage:
** rateLimitedFunc = rateLimit(function (i) { console.log(i) }, 500)
** for (var i=0; i < 10; i++) rateLimitedFunc(i)
*/
function rateLimit(func, delay) {
var queue = [],
processQueue = function() {
queue.shift().call();
if (queue.length) setTimeout(processQueue, delay);
};
return function() {
var args = [].slice.call(arguments), context = this;
queue.push(function() {
func.apply(context, args);
});
if (queue.length == 1) setTimeout(processQueue, 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment