Debounce with a cancel and flush method
Debounce with a cancel and flush method in JavaScript, so a pending call can be dropped on unmount or run early before a page closes. Node.js 24.
A debounced function that cannot be cancelled is a bug waiting for a component to unmount. Attach cancel and flush to it.
const debounce = (fn, wait) => {
let timer;
let pendingArgs;
const run = () => {
timer = undefined;
const args = pendingArgs;
pendingArgs = undefined;
if (args) fn(...args);
};
const debounced = (...args) => {
pendingArgs = args;
clearTimeout(timer);
timer = setTimeout(run, wait);
};
debounced.cancel = () => {
clearTimeout(timer);
timer = pendingArgs = undefined;
};
debounced.flush = () => {
clearTimeout(timer);
run();
};
return debounced;
};
const save = debounce((v) => console.log('saved', v), 1000);
save('draft 1');
save('draft 2');
save.flush();
save('draft 3');
save.cancel();saved draft 2flush runs the pending call now, with the latest arguments, and clears the timer. cancel drops it, so draft 3 never prints and no timer keeps the process alive. Functions can carry properties, which is how both are attached to debounced.
Call flush on beforeunload or when a form closes, and cancel when the work is no longer wanted.