Trivia Questions1 min readPremium

Debounce vs Throttle

Both techniques limit how often a function runs in response to rapid events such as typing, scrolling, or resizing. They differ in when the function runs. Here is how debounce vs throttle compares in practice, and CSS-Tricks has a good visual explanation too.

1. Debounce

Debounce waits until events stop for a given delay, then runs once. Every new event resets the timer.

function debounce(fn, delay) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

const search = debounce((q) => fetchResults(q), 300);
input.addEventListener('input', (e) => search(e.target.value));

If the user types continuously for 2 seconds, the search runs once, 300ms after the last keystroke.

2. Throttle

Throttle runs the function at most once per interval while events keep firing.

function throttle(fn, interval) {
  let last = 0;
  return function (...args) {
    const now = Date.now();
    if (now - last >= interval) {
      last = now;
      fn.apply(this, args);
    }
  };
}

window.addEventListener('scroll', throttle(updateProgressBar, 100));

During 2 seconds of continuous scrolling, updateProgressBar runs about 20 times at a steady rate.

3. Choosing: Debounce vs Throttle

Scenario Technique Why
Search-as-you-type API calls Debounce Only the final query matters
Autosave a form draft Debounce (with max wait) Save after a pause, but not never
Scroll position / infinite scroll checks Throttle Need regular updates during the scroll
Window resize layout recalculation Debounce or rAF throttle Final size matters; avoid thrashing
Rate-limiting button spam Throttle (leading) Run immediately, ignore repeats

4. Leading vs trailing

  • Trailing (default debounce): run after the burst ends.
  • Leading: run on the first event, then ignore until the wait passes. Good for buttons.
  • Lodash’s debounce supports a maxWait option, which guarantees a call at least every maxWait ms during a long burst (this is essentially how its throttle is built).

5. requestAnimationFrame throttling

For visual updates tied to scroll or pointer movement, throttle to the frame rate with requestAnimationFrame so you do at most one update per frame.

6. React gotcha

Creating a debounced function inside a component body creates a new debouncer (with a new timer) on every render, so it never actually debounces. Create it once with useMemo or useRef and cancel it on unmount.