Tech Interview RoomStudy guides

Frontend Coding

Implement debounce and throttle. When do you use each?

Intermediate · 2 min read · Lesson 3 of 10 in Frontend Coding

Problem

Some events fire dozens of times per second (input, scroll, resize, mousemove). Running expensive work (an API call, a layout calculation) on each one wastes resources and makes the UI janky.

Debounce

Wait until the events stop for wait ms, then run once with the last arguments. Use for: search-as-you-type, auto-save, validating a field, resize end.

Throttle

Run at most once every wait ms while events keep coming. Use for: scroll position tracking, infinite scroll checks, drag handlers, rate-limited analytics.

Details interviewers look for

  • Keep this and the arguments (use a regular function and fn.apply(this, args)).
  • A cancel() method (for component unmount) and optionally flush().
  • Leading vs trailing calls: throttle below runs on the leading edge and also once at the end, so the final position is never lost.
  • In React, create the debounced function once (useMemo/useRef) and cancel it in cleanup; otherwise a new timer is created on every render.
js
function debounce(fn, wait) {
  let timer = null;
  function debounced(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => { timer = null; fn.apply(this, args); }, wait);
  }
  debounced.cancel = () => { clearTimeout(timer); timer = null; };
  return debounced;
}

function throttle(fn, wait) {
  let last = 0;
  let trailing = null;
  let lastArgs, lastThis;
  function throttled(...args) {
    const now = Date.now();
    const remaining = wait - (now - last);
    lastArgs = args; lastThis = this;
    if (remaining <= 0) {                 // leading edge
      clearTimeout(trailing); trailing = null;
      last = now;
      fn.apply(this, args);
    } else if (!trailing) {               // schedule one trailing call
      trailing = setTimeout(() => {
        last = Date.now(); trailing = null;
        fn.apply(lastThis, lastArgs);
      }, remaining);
    }
  }
  throttled.cancel = () => { clearTimeout(trailing); trailing = null; last = 0; };
  return throttled;
}

// Demo
const sleep = ms => new Promise(r => setTimeout(r, ms));
const searched = [];
const search = debounce(q => searched.push(q), 50);
search('r'); search('re'); search('rea'); search('react');
await sleep(80);
assert.deepEqual(searched, ['react']);          // only the last call ran

const positions = [];
const onScroll = throttle(y => positions.push(y), 50);
for (let y = 0; y <= 100; y += 10) { onScroll(y); await sleep(10); }
await sleep(80);
assert.equal(positions[0], 0);                  // leading call
assert.equal(positions.at(-1), 100);            // trailing call keeps the final value
assert.ok(positions.length < 11);               // far fewer than 11 calls
console.log('debounce:', searched, 'throttle:', positions);

Example

Using it in React without recreating the timer each render:

jsx
function SearchBox({ onSearch }) {
  const debounced = useMemo(() => debounce(onSearch, 300), [onSearch]);
  useEffect(() => () => debounced.cancel(), [debounced]);
  return <input type="search" onChange={e => debounced(e.target.value)} />;
}

For scroll-driven visuals, requestAnimationFrame throttling (at most once per frame) is often better than a fixed delay.

Follow-up questions interviewers ask

Try answering each one before you open it.

Debounce vs throttle in one sentence?

Debounce says "run once after things calm down", throttle says "run regularly, but not more than every N ms"; a search box wants debounce, a scroll progress bar wants throttle.