Skip to content

Instantly share code, notes, and snippets.

@atomize
Created July 6, 2018 16:13
Show Gist options
  • Save atomize/b0228d583ade286631ce6c080861686c to your computer and use it in GitHub Desktop.
Save atomize/b0228d583ade286631ce6c080861686c to your computer and use it in GitHub Desktop.
Pure Javascript rate limit function. [https://jsfiddle.net/47cbj/56/]
function RateLimit(fn, delay, context) {
var queue = [], timer = null;
function processQueue() {
var item = queue.shift();
if (item)
fn.apply(item.context, item.arguments);
if (queue.length === 0)
clearInterval(timer), timer = null;
}
return function limited() {
queue.push({
context: context || this,
arguments: [].slice.call(arguments)
});
if (!timer) {
processQueue(); // start immediately on the first invocation
timer = setInterval(processQueue, delay);
}
}
}
function foo(param1, param2) {
var p = document.createElement('p');
p.innerText = param1 + (param2 || '');
document.body.appendChild(p);
}
foo('Starting');
var bar = RateLimit(foo, 1000);
bar(1, 'baz');
bar(2, 'quux');
bar(3);
bar(4, 'optional');
bar(5, 'parameters');
bar(6);
bar(7);
bar(8);
bar(9);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment