Debounce & Throttle — Performance

Debounce delays a function until the events stop for delay ms: every call runs clearTimeout(timer) and then timer = setTimeout(() => fn.apply(this, args)…

You type "soup" into a search box. Four letters, four requests to the server, and the results of the first three are thrown away at once because you weren't done typing. On a phone with a so-so signal, those requests also fight each other for the connection.

Events such as input, scroll and resize can fire dozens of times a second. If every event starts heavy work right away, such as a request to the server, the page gets sluggish and the server gets flooded. Debounce and throttle are two ways to limit how often a function actually runs. Picture a lift door: it only closes after 3 seconds with nobody stepping in, and every person who steps in starts the count again. That is debounce. Now picture a water dispenser that gives one cup every 3 seconds, however many times you press its button. That is throttle.

Debounce: wait until it stops

Debounce delays a function until the events stop for delay ms. Every new call cancels the old schedule and sets a new one.

Time You type What happens
0 ms s schedule set: run at 300 ms
100 ms so old schedule cancelled, new one: 400 ms
200 ms sou cancelled again, new one: 500 ms
300 ms soup cancelled again, new one: 600 ms
600 ms (quiet) search("soup") runs, the request is sent

Four keystrokes, 1 request, with the last word.

function debounce(fn, delay) {
  let timer = null;

  return function (...args) {
    clearTimeout(timer); // cancel the previous schedule
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

const search = debounce((word) => {
  console.log("fetch /api/search?q=" + word);
}, 300);

search("s");
search("so");
search("sou");
search("soup");
// 300 ms after the last call, only once:
// fetch /api/search?q=soup

Three things must hold: before delay has passed, fn has not run at all; three calls in a row give only one run; and after it runs, the wrapper can be used again for the next wave.

Debounce doesn't control the order of the replies. Say you pause for a moment after "soup", its request goes out, but the server is slow. Then you type "soup recipe", and the reply for "soup recipe" arrives first. The late "soup" reply then replaces it, so the wrong results show. The fix: cancel the old request with an AbortController before sending the new one.

let controller = null; // the AbortController of the latest request

async function search(word) {
  controller?.abort(); // cancel the previous request if it has not finished
  controller = new AbortController();
  try {
    const res = await fetch("/api/search?q=" + word, { signal: controller.signal });
    show(await res.json());
  } catch (err) {
    if (err.name !== "AbortError") throw err; // cancelled on purpose, not an error
  }
}

const searchDebounced = debounce(search, 300);

show is your own function that draws the results on the page. In Chromium 156, with a 900 ms reply for "soup" and a 100 ms reply for "soup recipe", this code shows only the "soup recipe" results. Without the abort() line, the "soup recipe" results show and are then replaced by the "soup" results.

Throttle: at most once per interval

Throttle runs a function at most once every interval ms, for as long as the events keep coming. The events in between are dropped.

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(() => {
  console.log("position", window.scrollY);
}, 300));

Scrolling for 1 second fires an event roughly every 16 ms, about 60 events. With a 300 ms throttle, the handler runs at 0, 304, 608 and 912 ms: 4 times, and it keeps running regularly while the scroll goes on. A 300 ms debounce in the same situation runs once, 300 ms after the scroll stops.

Leading and trailing edge

The edge is when the function runs within one burst of events: at the start (leading) or at the end (trailing).

Libraries such as Lodash have { leading, trailing } options for both.

Which one to pick

Situation Pick Why
Search box with a request to the server debounce the result for the last word is enough
Auto-saving a draft debounce save once the person stops typing
A scroll that calls an API while scrolling throttle needs regular updates while moving
Resizing the window, then redoing the layout debounce once, after it is done, is enough
Pointer position while dragging throttle has to keep following the movement

The rule of thumb: debounce waits for the activity to stop, throttle limits how often it runs per interval.

⚠️ Why does every keystroke still send a request?

TL;DR: Debounce delays a function until the events stop for delay ms: every call runs clearTimeout(timer) and then timer = setTimeout(() => fn.apply(this, args), delay), so only the last call runs, with its arguments ("soup" typed in 4 letters, 1 request). Throttle runs a function at most once per interval while the events keep coming (1 second of scrolling with a 300 ms throttle runs 4 times). Leading means running at the start of a burst, trailing at its end. Use debounce for search, drafts and resize. Use throttle for scroll and drag that need updates while moving.

⚡ Debounce: wait until it stops

Write:

return function (...args) {
  clearTimeout(timer);
  timer = setTimeout(() => fn.apply(this, args), delay);
};
Guess first: you type "soup" into a search box with a 300 ms debounce. How many requests go out?

One, with the last word. Every keystroke cancels the old schedule with clearTimeout, and only 300 ms after the last keystroke does search("soup") run.

Meaning: debounce returns a wrapper. Call debounce once, keep the result, and call that result on every event.

⚡ Throttle: at most once per interval

Meaning: Throttle runs a function at most once every interval ms while the events keep coming. One second of scrolling with a 300 ms throttle runs 4 times, regularly, while the scroll goes on.

⚡ Which one to pick

Meaning: Debounce waits for the activity to stop, throttle limits how often it runs per interval. Search, drafts and resize get debounce. Scroll and drag that need updates while moving get throttle.

What you will learn