Debounce async functions and reject or resolve, as promised :)
let delay = 300; // ms
let doStuff = Debouncer.create(function (x) {
console.log("Finally!", x);
}, 300);
doStuff("a"); // debounced
doStuff("b"); // debounced
doStuff("c"); // "Finally! c" (after 300ms)
- Rejects when
- the call is debounced (due to a subsequent call)
- your function has not yet resolved (it's still in progress)
- your function rejects (or throws)
- Resolves when
- the call is not debounced AND your function resolves
<script src="https://unpkg.com/@root/debounce"></script>
Or
<script src="https://unpkg.com/@root/debounce@v1.0.1/debounce.min.js"></script>
var Debouncer = window.Debouncer;
Debouncer.create(fn, ms);
# node.js
npm install --save @root/debounce
var Debouncer = require("@root/debounce");
Debouncer.create(fn, ms);
async function doStuff() {
console.log("Doing important things...");
await sleep(100);
console.log("Did important things!");
}
let doStuffDebounced = Debouncer.create(doStuff, 300);
doStuffDebounced(); // rejected
doStuffDebounced(); // rejected
doStuffDebounced(); // succeeds
setTimeout(function () {
// rejected because doStuff is running
doStuffDebounced();
}, 400);
setTimeout(function () {
// succeeds because doStuff has finished and there's nothing to cancel it
doStuffDebounced();
}, 600);
// helper
async function sleep(delay) {
return new Promise(function (resolve, reject) {
setTimeout(resolve, delay);
});
}