← Back to JavaScript, page 2

javascript-0031 · Medium mid

What is the difference between debounce and throttle? Implement both.

Debounce waits until calls stop for a given time and then runs once, which suits search boxes and resize handlers. Throttle runs at most once per time interval no matter how often it is called, which suits scroll and drag handlers. Both are built from closures that remember a timer or a last-run time.

Full answer

Both techniques limit how often a function runs when an event fires many times in a short period.

Debounce delays execution until there has been a quiet period. Every new call cancels the previous timer and starts a new one. If a user types five letters quickly, a debounced search with a 300 ms wait fires once, 300 ms after the last key. Use it when only the final value matters: search suggestions, form validation, auto-save, and window resize.

Throttle guarantees a steady maximum rate. The function runs at the first call, and further calls are ignored until the interval has passed. During a long scroll, a throttled handler with a 100 ms limit runs about ten times per second, not hundreds of times. Use it when intermediate results matter: scroll position, mouse move, and drag.

A debounce can use a leading option to run at the first call instead of the last, and many implementations add cancel and flush methods. A throttle can also run a trailing call so the final state is not missed.

Both rely on closures. The returned wrapper keeps a timer id or a timestamp in the outer function's scope. It must forward this and the arguments to the real function. For timing, throttle uses a clock. Accepting the clock as a parameter makes it easy to test without waiting.

javascript
function debounce(fn, wait) {
  let timerId;
  return function (...args) {
    clearTimeout(timerId);
    timerId = setTimeout(() => fn.apply(this, args), wait);
  };
}

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

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

(async () => {
  const search = debounce((text) => console.log('debounced search for:', text), 60);
  for (const text of ['j', 'ja', 'jav', 'java']) {
    search(text);
    await sleep(15);
  }
  await sleep(120);

  let clock = 0;
  const onScroll = throttle((position) => console.log('throttled at', position), 50, () => clock);
  for (clock = 0; clock <= 120; clock += 10) {
    onScroll(clock);
  }
})();

Run with Node.js v24.22.1 as js-31.js; two runs gave identical output. Output: debounced search for: java throttled at 0 throttled at 50 throttled at 100

Key points

  • Debounce: run once after calls stop for the wait time.
  • Throttle: run at most once per interval.
  • Debounce suits final-value cases; throttle suits continuous events.
  • Both use closures to hold a timer id or last-run time.
  • Forward this and arguments; consider cancel, leading, and trailing options.

Common mistakes

  • Creating a new debounced function on every render or event, so each call has its own timer and nothing is limited.
  • Losing this or arguments by calling fn() instead of fn.apply(this, args).
  • Using debounce for scroll-position tracking, which only reports after the user stops.
  • Forgetting to cancel pending debounced calls when a component or page is removed.

Follow-ups

  • How would you add leading and trailing options to debounce?
  • Which browser APIs reduce the need for throttle, such as IntersectionObserver or requestAnimationFrame?
  • How would you test a debounced function without waiting for real time?

Tips

  • Use the words "wait until calls stop" for debounce and "at most once per interval" for throttle; they are the two sentences interviewers want.
  • Give a concrete case for each: search box and scroll handler.
  • When coding, write the wrapper as a normal function, not an arrow, so this can be forwarded.