Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

Debounce & Throttle — JavaScript interview guide

20 / 23Interview CodingHigh priorityMedium 30 min

Debounce & Throttle

Debounce waits until calls STOP for a while, then runs once. Throttle runs at most once every X milliseconds while calls keep coming.

See it run

Press Play, or step with Next. Watch the highlighted line, the Call Stack and memory change together.

Debounce: only the last call wins

Execution phaseStep 1/8
script.js
1function debounce(fn, delay) {
2 let timer;
3 return (...args) => {
4 clearTimeout(timer);
5 timer = setTimeout(() => fn(...args), delay);
6 };
7}
8
▶const search = debounce(q => console.log("API:", q), 300);
10
11search("r"); // user types at 0ms
12search("re"); // 100ms
13search("rea"); // 200ms
Call Stack
last in, first out
Globalrunning
Memory / Scope
Global
searchƒ debounced
Closure (debounce)
timerundefined
delay300
Web APIs (browser)
runs outside JS

empty

Event Loop

Waits until the Call Stack is empty. Microtasks always go first.

Microtask Queue
promises · high priority

empty

Callback Queue
setTimeout, events

empty

Console

nothing printed yet

What happens:debounce returns a new function. Thanks to a closure, every call to search shares the SAME timer variable.

Tip: click the box and use ← → keys to step, space to play.

Explained simply

When to use which

Debounce: search input, autosave, window resize end. Throttle: scroll position, mouse move, infinite scroll checks.

Throttle implementation

Run immediately, then ignore calls until the wait time passes.

function throttle(fn, wait) {
  let last = 0;
  return (...args) => {
    const now = Date.now();
    if (now - last >= wait) {
      last = now;
      fn(...args);
    }
  };
}

Remember this

  • Both rely on a closure holding a timer or timestamp.
  • Debounce can have leading and trailing options.
  • Remember to cancel on unmount in React.

Interview questions

Debounce vs throttle in one line?

Debounce: run after the user stops. Throttle: run at a steady maximum rate while the user continues.

Practice

  1. Add a cancel() method to debounce.
  2. Write a useDebounce React hook.

Keep learning