Created
October 12, 2016 19:15
-
-
Save anthonyserious/51e211cf98381bda9269ec1bd1c64b7a to your computer and use it in GitHub Desktop.
Wrap functions to stagger (vs. lodash _.throttle, which drops throttled messages)
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
"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