DEV Community

Leo Ho
Leo Ho

Posted on

Debounce vs throttle: two tiny helpers, one mental model

Search-as-you-type can fire an input handler 20 times in 800 ms. A scroll listener can fire once per frame. Neither problem is fixed by making the handler faster; it is fixed by deciding how often the handler is allowed to run.

The mental model

  • Debounce collapses a burst into one call: after the last call, wait wait ms, then run once.
  • Throttle guarantees spacing: run at most once per wait ms while calls keep coming, then run once more with the final state.

Debounce answers "did the user stop?" Throttle answers "how often do we allow work?" If you cannot say which question your feature asks, you are about to pick the wrong one. Both helpers below are trailing by default; add a leading branch only when the first call must be instant.

The implementation

No dependencies, no classes, no this games:

const debounce = (fn, wait) => {
  let t;
  return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), wait); };
};

const throttle = (fn, wait) => {
  let t, last = 0, args;
  return (...a) => {
    args = a;
    const left = wait - (Date.now() - last);
    if (left <= 0) { clearTimeout(t); t = undefined; last = Date.now(); fn(...args); }
    else if (!t) t = setTimeout(() => { t = undefined; last = Date.now(); fn(...args); }, left);
  };
};

(async () => {
  const wait = 40;
  let d = 0, t = 0;
  const a = debounce(() => d++, wait), b = throttle(() => t++, wait);
  for (let i = 0; i < 20; i++) { a(i); b(i); await new Promise((r) => setTimeout(r, 5)); }
  await new Promise((r) => setTimeout(r, wait * 2));
  console.log({ debounced: d, throttled: t });
})();
Enter fullscreen mode Exit fullscreen mode

debounce needs one variable; throttle needs three: the last run time, a pending trailing timer, and the latest arguments. That extra state is why throttle is the one people get subtly wrong.

Prove the difference

Run the file with node timing.js. It prints:

{ debounced: 1, throttled: 4 }
Enter fullscreen mode Exit fullscreen mode

One call versus four. Debounce swallowed the burst and ran after silence. Throttle ran on the leading edge, then every 40 ms, with one trailing call so the final value is not lost.

Which one where

Use debounce for search suggestions, validation, autosave, and expensive recalculation. Use throttle for scroll progress, mousemove, resize rendering, and analytics flushes. The reverse choices fail in opposite directions: a debounced scroll handler does nothing while the user is scrolling, which reads as lag, and a throttled search sends requests for half-typed words, so the result list flickers between guesses.

The bug debounce does not fix

Debounce reduces the number of requests, not their order. Two requests 300 ms apart can still return out of order, and the older response can overwrite the newer one. Keep an AbortController per request and abort the previous one inside the handler, or compare a request id before rendering. Debounce is a timing tool; ordering is a concurrency problem.

Three details that bite

  • this. The arrows above keep the module's this. For object methods, use function and fn.apply(this, args).
  • Trailing arguments. The throttle remembers the latest arguments, so the final call sees the final state. Naive versions replay the arguments from the first event in the window.
  • Paint-only handlers. requestAnimationFrame beats a timer for visual updates, because it aligns work with the browser's frame.

If you want an input-heavy surface to test against, these two counters run entirely in the browser with no upload and no account: English word and character counter and Vietnamese word and character counter. Their handler recomputes counts and keyword density on every keystroke, which is exactly the workload this post is about.

Timing code is easy; choosing the contract is the work. Debounce when only the last event matters, throttle when every event matters but the budget does not.

— Leo Ho

Top comments (0)