What is debounce?

Debouncing delays running a function until a burst of calls has stopped for a given time, so only the last call in the burst actually runs; it is the standard fix for expensive work triggered by rapid events like typing or resizing.

How it behaves

Every call resets a timer. The wrapped function runs only when no new call has arrived for wait milliseconds. Ten keystrokes in quick succession produce one search request, after the user pauses.

Typical uses

  • Search-as-you-type and autocomplete requests.
  • Validating a form field after the user stops typing.
  • Saving a draft automatically.
  • Recalculating layout after a window resize finishes.

Variants

  • Trailing (default): run after the pause, with the latest arguments.
  • Leading: run immediately on the first call, then ignore calls until things are quiet. Good for buttons to prevent double submits.
  • maxWait: guarantee a call at least every N ms even if events never stop (Lodash supports this).
  • cancel / flush: cancel a pending call (e.g. on unmount) or run it now.

Debounce vs throttle

Debounce waits for quiet and runs once at the end; throttle runs at most once per interval while events keep coming. Use debounce when only the final value matters.

In React

Create the debounced function once (useMemo/useRef), not on every render, and cancel it on unmount. Often a useDebounce(value, delay) hook is simpler.

Code example

js
1function debounce(fn, wait, { leading = false } = {}) {
2 let timer = null;
3 const debounced = function (...args) {
4 const callNow = leading && timer === null;
5 clearTimeout(timer);
6 timer = setTimeout(() => {
7 timer = null;
8 if (!leading) fn.apply(this, args); // trailing call with the latest args
9 }, wait);
10 if (callNow) fn.apply(this, args);
11 };
12 debounced.cancel = () => {
13 clearTimeout(timer);
14 timer = null;
15 };
16 return debounced;
17}
18
19// Simulate fast typing: only the last value is searched
20const search = debounce((q) => console.log("searching for:", q), 100);
21["r", "re", "rea", "reac", "react"].forEach((q, i) => setTimeout(() => search(q), i * 20));
22// -> searching for: react (once)
23
24// Leading: run on the first click, ignore the rest of the burst
25const submit = debounce(() => console.log("submitted once"), 100, { leading: true });
26submit();
27submit();
28submit();
29
30await new Promise((r) => setTimeout(r, 300));

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app