Skip to the content

Lesson 78 of 296

debounce and throttle

On this page

The task

"Implement debounce(fn, delay)." Often followed by: "Now implement throttle(fn, interval). What is the difference?"

What they are for

Some events fire very often: typing, scrolling, resizing the window, moving the mouse. Running expensive code (an API request, a layout calculation) on every single event wastes resources and makes the page slow.

DebounceThrottle
RuleWait until the events stop for a set time, then run onceRun at most once per set time while the events continue
ExampleSearch box: only search when the user pauses typing for 300 msScroll handler: update a progress bar at most every 100 ms while scrolling
If events never stopIt never runsIt runs regularly

Plain way to remember:

  • Debounce: "wait until they stop, then do it once".
  • Throttle: "do it, then not again until the time is up".

What the interviewer is checking

  • Closures, to keep the timer between calls (Lesson 53).
  • setTimeout and clearTimeout.
  • Keeping this and the arguments.
  • Edge cases: leading or trailing calls, and cancelling.

Questions to ask first

  • "Should it run at the end of the wait (trailing), at the start (leading), or both?"
  • "Do you want a cancel method?"

debounce, step by step

  1. Keep a timer ID in a closure.
  2. Every call: cancel the previous timer, then start a new one.
  3. When a timer finally completes (no new call arrived in time), run the function with the latest arguments.
function debounce(fn, delay) {
  let timerId;

  function debounced(...args) {
    clearTimeout(timerId);
    timerId = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  }

  debounced.cancel = () => clearTimeout(timerId);
  return debounced;
}
  • debounced is a normal function so it receives the caller's this. The arrow function inside setTimeout keeps that this.
  • clearTimeout(undefined) is safe on the first call.

Usage:

const search = debounce((text) => {
  fetch(`/api/search?q=${encodeURIComponent(text)}`);
}, 300);

input.addEventListener("input", (e) => search(e.target.value));

Test it

const calls = [];
const d = debounce((x) => calls.push(x), 50);
d(1); d(2); d(3);
after 100 ms: calls is [3]

throttle, step by step

This version runs immediately on the first call (leading), and also makes sure the last call in a burst is not lost (trailing):

function throttle(fn, interval) {
  let lastRun = 0;
  let timerId = null;
  let lastArgs;
  let lastThis;

  return function throttled(...args) {
    const now = Date.now();
    const remaining = interval - (now - lastRun);
    lastArgs = args;
    lastThis = this;

    if (remaining <= 0) {
      clearTimeout(timerId);
      timerId = null;
      lastRun = now;
      fn.apply(lastThis, lastArgs);
    } else if (!timerId) {
      timerId = setTimeout(() => {
        lastRun = Date.now();
        timerId = null;
        fn.apply(lastThis, lastArgs);
      }, remaining);
    }
  };
}
  • If enough time has passed since the last run, run now.
  • Otherwise, if no trailing run is scheduled yet, schedule one for when the interval ends, using the latest arguments.

Simpler version (leading only, the most common first answer in interviews):

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

Mention that it drops the last call of a burst, then offer the full version.

Test it

const t = [];
const th = throttle((x) => t.push(x), 100);
th(1); th(2); th(3);
after 150 ms: t is [1, 3]   (1 ran now; 3 was the trailing call)

Follow-up questions

  • "Add a leading option to debounce." Run on the first call if no timer is active, then ignore calls until the wait ends.
  • "Why use these in React?" Search inputs and resize handlers. In React, create the debounced function once (for example with useMemo or useRef), otherwise each render makes a new one with a new timer (Part 12).
  • "What about requestAnimationFrame?" For visual updates during scroll, requestAnimationFrame limits work to once per screen refresh; it is a natural throttle for animations.

Common mistakes

  • Creating the timer variable inside the returned function, so every call has its own timer and nothing is cancelled.
  • Losing this or the arguments.
  • Mixing up which one waits for silence (debounce) and which one runs regularly (throttle).

How to say it in an interview

"Debounce delays running until calls have stopped for the given time, so I keep a timer in a closure, clear it on every call and set a new one; it suits search-as-you-type. Throttle runs at most once per interval while calls continue; I store the last run time, run immediately if the interval has passed, and otherwise schedule one trailing call with the latest arguments, which suits scroll and resize. Both preserve this and the arguments, and debounce can expose a cancel method."

Key words

WordMeaning
DebounceRun once after the calls stop for a set time
ThrottleRun at most once per set time
Leading callRunning at the start of a burst of calls
Trailing callRunning at the end of a burst of calls
Timer IDThe value returned by setTimeout, used to cancel it

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.