Created
July 6, 2018 16:13
-
-
Save atomize/b0228d583ade286631ce6c080861686c to your computer and use it in GitHub Desktop.
Pure Javascript rate limit function. [https://jsfiddle.net/47cbj/56/]
This file contains hidden or 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
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