Created
April 27, 2017 09:48
-
-
Save blackChef/404ace3ac4e92efbfc69c970caf04776 to your computer and use it in GitHub Desktop.
debounce with queue
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
let debounceWithQueue = function(fn, wait = 0) { | |
let timeoutId; | |
let argsQueue = []; | |
return function(arg) { | |
argsQueue = argsQueue.concat(arg); | |
if (timeoutId !== undefined) { | |
clearTimeout(timeoutId); | |
} | |
timeoutId = setTimeout(function() { | |
fn(argsQueue); | |
timeoutId = undefined; | |
argsQueue = []; | |
}, wait); | |
}; | |
}; | |
let onMsg = debounceWithQueue(function(args) { | |
console.log(args); | |
}, 100); | |
let flushMsg = function() { | |
let i = 100; | |
while (i) { | |
onMsg(i); | |
i-=1; | |
} | |
}; | |
flushMsg(); // [100, 99, 98, ...1] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment