Frontend Case Studies

Topic F5

Debounce and throttle

Waiting for the user to stop, or capping how often: for events that fire in bursts.

8 min · beginner

Watch: count the green blocks in the front row. Each one is a time the site asks the server. Fewer means less work for the server.

lettersasks server0 s0.5 s1 s1.5 s
  • happening now
  • letters already typed
  • a question to the server
Step 1 of 9

Someone types "sweater" into an online shop's search box, pausing twice to think. In this version, every letter makes the site ask the server straight away: "what products match this text?"

A site doesn't need to ask the server for every letter. It can wait for the person to stop typing, or cap how often it asks.

Like a lift and a traffic light

  • Debounce is like lift doors: every time someone steps in, the doors wait again. The lift only leaves after a few seconds with nobody stepping in.
  • Throttle is like a traffic light: however many cars arrive, it turns green at most once per cycle.
Code, for programmersBoth in a few lines
function debounce(fn, wait) {
  let timer;
  return (...args) => {
    clearTimeout(timer);                          // every call resets the wait
    timer = setTimeout(() => fn(...args), wait);
  };
}

function throttle(fn, gap) {
  let last = 0;
  return (...args) => {
    const now = Date.now();
    if (now - last >= gap) { last = now; fn(...args); }   // otherwise drop it
  };
}

input.addEventListener("input", debounce((e) => search(e.target.value), 300));
window.addEventListener("scroll", throttle(updateProgressBar, 100));

The throttle above only fires at the start (leading). The full version (like lodash.throttle) also makes one last call at the end (trailing), so the final value is never missed.

Which to use

CaseChoose
Search as you type, username checksdebounce (200–400 ms)
Autosaving a draftdebounce (1–2 s), plus save when the tab closes
Scroll, resize, drag, mouse movesthrottle, or requestAnimationFrame
A pay button clicked twicedisable the button + an idempotency key on the server

Quiz

  1. A user types 10 letters quickly without pausing, with a 300 ms debounce. How many requests?

  2. To update a progress bar while scrolling, which fits better?

  3. What's the weakness of a leading-only throttle?

0 of 3 answered.