Skip to content
jshacks.dev
Functions

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.

1 min read
Summarize in AI

A debounced function that cannot be cancelled is a bug waiting for a component to unmount. Attach cancel and flush to it.

JavaScript
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();
Text
saved draft 2

flush 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.

Taggednode 24
Share

More snippets

Functions

Write a once function

Write a once function in JavaScript that runs a callback a single time and returns the cached result after that. Works in any Node.js, ES2015 or later.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.