Debounce & Throttle: Taming Event Floods

Debounce & Throttle: Taming Event Floods in JavaScript: Some events fire absurdly often. A handler can run dozens of times a second.

Concept Explanation

Some events fire absurdly often. A scroll handler can run dozens of times a second. A keyup handler on a search box runs once per keystroke, which means a user typing "javascript tutorial" just asked your API nineteen questions and only cared about the last one.

Debounce and throttle both fix this, and they are constantly confused, so anchor them with two images:

Debounce is an elevator door. Every new person walking in resets the timer. The doors only close once nobody has arrived for a few seconds. You get exactly one departure at the end of the burst.

Throttle is a metronome. It fires on a fixed beat and ignores everything in between. During a five-second scroll you get one call every 100ms, steadily, not one call at the end.

The choice follows from the question: do you want the final value, or do you want regular updates along the way?


Syntax or Core Structure

Debounce

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

const search = debounce((q) => fetch('/api/search?q=' + q), 300);
input.addEventListener('input', (e) => search(e.target.value));

Throttle

function throttle(fn, limit = 100) {
  let waiting = false;
  let lastArgs = null;
  return function (...args) {
    if (waiting) { lastArgs = args; return; }
    fn.apply(this, args);
    waiting = true;
    setTimeout(() => {
      waiting = false;
      if (lastArgs) { fn.apply(this, lastArgs); lastArgs = null; }
    }, limit);
  };
}

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

Cancellable debounce

function debounce(fn, delay = 300) {
  let timer;
  const wrapped = (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
  wrapped.cancel = () => clearTimeout(timer);
  return wrapped;
}

Which One, When

SituationUseWhy
Search-as-you-typeDebounceOnly the final query matters
Auto-save a draftDebounceSave when they pause, not per character
Validating a field on blur-ish inputDebounceDo not shout at a half-typed email
Scroll position / sticky headerThrottleYou need steady updates during the scroll
Window resize re-layoutThrottle, then a trailing debounceSmooth during, correct at the end
Rate-limiting an analytics pingThrottlePredictable ceiling on call volume
Animating with scroll positionrequestAnimationFrameAligns with the frame, better than either

Real World Example

An autocomplete that cost real money. A team shipped search-as-you-type straight onto input with no limiter. Each keystroke hit a paid geocoding API. Traffic looked fine in testing, then the bill arrived: average query length was around fourteen characters, so they were paying fourteen times per search. Adding a 300ms debounce cut API calls by roughly 90% and made the UI feel better, because results stopped flickering and being replaced mid-read.


Common Mistakes

  • Creating the debounced function inside the handler. onInput={debounce(fn, 300)} in a React render makes a brand-new timer on every keystroke, so nothing is ever debounced. Create it once with useMemo or outside the component.
  • Debouncing something that needs to feel instant. A debounced button click looks like a broken button.
  • Throttling with a long interval and no trailing call. The final scroll position never arrives and your header sticks in the wrong state.
  • Losing this. Use fn.apply(this, args) or arrow functions consistently, or method calls break.
  • Not cancelling on unmount. A pending timer fires against a component that no longer exists.
  • Debouncing instead of cancelling in-flight requests. Debounce reduces requests; it does not stop an old slow response from overwriting a newer fast one. Use AbortController for that.

Best Practices

  • Pick delays from behaviour, not taste: 250-400ms for typing, 100-150ms for scroll, and requestAnimationFrame for anything that touches layout.
  • Expose a cancel method and call it in your cleanup path.
  • Combine debounce with AbortController for search: fewer requests and no out-of-order results.
  • Prefer IntersectionObserver and ResizeObserver over throttled scroll and resize handlers. The platform already solved those cases more efficiently.
  • Reach for lodash's debounce/throttle in production; they handle leading and trailing edges, maxWait, and cancellation properly.

Practice Exercises

  1. The Debouncer: Build a debounce function from scratch that waits 300ms before running, then add a cancel method and prove it works.
  2. The Counter Comparison: Attach a debounced and a throttled handler to the same scroll event, log a counter from each, and scroll for five seconds. Explain the difference in the two totals.
  3. The Race Fix: Build a debounced search where a slow earlier response could overwrite a fast later one, reproduce the bug, then fix it with AbortController.