4. Implement throttle(fn, wait) — Frontend Interview Question

medium

throttle is debounce's twin and interviewers love asking them back to back. The one-line distinction to have ready: debounce waits for quiet; throttle fires on a steady cadence.

The idea

Remember when the function last ran. On each call, work out how much of the wait window remains:

  • Window elapsed → run now (leading edge) and reset the clock.
  • Still inside the window → schedule one trailing call so the last event in a burst isn't dropped.

Follow-ups interviewers love

  • "Leading only or trailing only?" → gate each branch behind an { leading, trailing } option.
  • "Why store timer in the closure?" → so a single pending trailing call exists per throttled function.
  • "throttle vs debounce for a scroll handler?" → throttle, so the UI updates at a steady rate instead of only after scrolling stops.

What to practice

Write it from scratch, then add a { trailing: false } option that skips the trailing call. If you can explain when each edge matters, you're ready.

More questions

index.js
function throttle(fn, wait) {
  // your code here
}

// Try it:
const log = throttle((x) => console.log('tick', x), 300);
window.addEventListener?.('resize', () => log(Date.now()));

Tests

Test Code

Enter JavaScript that runs after your solution. It should return a value or a Promise.