Skip to the page

Polyfills interviewers ask · core

Throttle (and why the flag version loses the last call)

Throttle lets a function run at most once per wait ms: the first call can run immediately (leading) and, if more calls arrive during the wait, one trailing call runs at the end with the latest arguments, so the final state is never lost.

The notes

What you must know

  • Timestamp plus trailing timer: compute remaining = wait - (now - last); if remaining <= 0 run now; else if no timer, schedule one for remaining ms that runs with the latest arguments.
  • leading and trailing options; cancel().
  • The simple 'flag + setTimeout' version drops the last call, so the final scroll position or size is never handled.
  • For visual updates, throttle with requestAnimationFrame: schedule at most one frame callback and use the latest value.
  • Uses: scroll, mousemove, drag, resize, analytics pings.
  • Throttle = steady rate during activity; debounce = once after activity stops. Throttling promises (limiting concurrency) is a different problem: a pool.

The red pen

Common traps: mistake → fix

  • Mistake: The flag version is fine

    Fix: it loses the final call.

  • Mistake: Throttle and debounce are the same

    Fix: different timing behaviour.

  • Mistake: Computing the trailing delay as a full wait

    Fix: use the remaining time.

Easy to hard

Questions interviewers ask, easy to hard

  1. Implement throttle(fn, wait). (Dream11, Google, Rippling)
  2. Make sure the last call isn't lost.
  3. Add leading/trailing options and cancel().
  4. Throttle a scroll handler with requestAnimationFrame.
  5. How do you unit-test it?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview