Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var stack = [],
- timer = null;
- function process() {
- var item = stack.shift();
- // process
- if (stack.length === 0) {
- clearInterval(timer);
- timer = null;
- }
- }
- function queue(item) {
- stack.push(item);
- if (timer === null) {
- timer = setInterval(process, 500);
- }
- }
- function RateLimit(fn, delay, context) {
- var canInvoke = true,
- queue = [],
- timeout,
- limited = function () {
- queue.push({
- context: context || this,
- arguments: Array.prototype.slice.call(arguments)
- });
- if (canInvoke) {
- canInvoke = false;
- timeEnd();
- }
- };
- function run(context, args) {
- fn.apply(context, args);
- }
- function timeEnd() {
- var e;
- if (queue.length) {
- e = queue.splice(0, 1)[0];
- run(e.context, e.arguments);
- timeout = window.setTimeout(timeEnd, delay);
- } else
- canInvoke = true;
- }
- limited.reset = function () {
- window.clearTimeout(timeout);
- queue = [];
- canInvoke = true;
- };
- return limited;
- }
- function foo(x) {
- console.log('hello world', x);
- }
- var bar = RateLimit(foo, 1e3);
- bar(1); // logs: hello world 1
- bar(2);
- bar(3);
- // undefined, bar is void
- // ..
- // logged: hello world 2
- // ..
- // logged: hello world 3
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement