Skip to content
jshacks.dev
Functions

Write a debounce with leading and trailing options

Write a debounce with leading and trailing options in JavaScript, so a call can fire at the start, the end of the burst, or both. Node.js 24.

1 min read
Summarize in AI

Plain debounce waits until calls stop. Sometimes you want the first call right away, such as a save button that reacts at once and ignores repeats.

JavaScript
const debounce = (fn, wait, { leading = false, trailing = true } = {}) => {
  let timer;
  let pending;
  return (...args) => {
    const startOfBurst = timer === undefined;
    pending = args;
    clearTimeout(timer);
    if (startOfBurst && leading) fn(...args), (pending = null);
    timer = setTimeout(() => {
      timer = undefined;
      if (trailing && pending) fn(...pending);
      pending = null;
    }, wait);
  };
};

const log = debounce((x) => console.log('call', x), 20, { leading: true });
log(1); log(2); log(3);
Text
call 1
call 3

The first call starts a burst and fires at once. The later calls reset the timer and store the latest arguments. When 20 ms pass without a call, the trailing edge fires with 3. With leading: true and trailing: false only call 1 is printed.

When the burst has only one call and leading is on, it fires immediately and the trailing call is skipped, because pending was cleared. Utility libraries implement the same options with more edge cases.

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.