Skip to content

Instantly share code, notes, and snippets.

@anthonyserious
Created October 12, 2016 19:15
Show Gist options
  • Save anthonyserious/51e211cf98381bda9269ec1bd1c64b7a to your computer and use it in GitHub Desktop.
Save anthonyserious/51e211cf98381bda9269ec1bd1c64b7a to your computer and use it in GitHub Desktop.
Wrap functions to stagger (vs. lodash _.throttle, which drops throttled messages)
"use strict";
module.exports = function stagger(fn, ms) {
let queue = [];
let running = false;
let flush = () => {
if (queue.length === 0) {
running = false;
return;
}
running = true;
setTimeout(() => {
fn.apply(this, queue.shift());
return flush();
}, ms);
};
return function staggered() {
let args = Array.prototype.slice.call(arguments);
queue.push(args);
if (!running) {
return flush(queue);
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment