Last active
December 20, 2015 08:59
-
-
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)
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
/* | |
** 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