Remember when the function last ran. A call runs if wait ms have passed and is otherwise dropped, and use fn.apply(this, args) so methods keep their this. That basic version loses the last call inside a window, which interviewers poke at, so add a trailing edge: store the latest arguments and set one timer for the end of the window to run them. Then the first call runs at once, the final value always lands, and runs are never closer than wait. Then the extras: leading/trailing options, cancel() for unmount, flush(), and requestAnimationFrame when the real rate limit is one frame.
Implement throttle, for example allowing an input function to run at most once every 50 milliseconds.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
Remember when the function last ran. A call runs only if wait ms have passed since then, and is otherwise dropped. That's the throttle you can write in a minute, and it keeps this and the arguments. The last check shows its flaw: the final call inside a window never runs, so a scroll handler can stop one position short.
// Run at most once per `wait` ms: the first call runs at once, calls inside the window are dropped.function throttle(fn, wait) {let last = -Infinity;return function (...args) {const now = Date.now();if (now - last >= wait) {last = now;fn.apply(this, args);}};}
passes 3 checks run on every build, against the native method where there is one
- at most once per window, first call at once
- keeps this and arguments
- the weakness: the last call inside a window is lost
Store the latest call's arguments and this. If the window has passed, run now (the leading edge). Otherwise make sure one timer is set for the moment the window ends, and run the stored call then (the trailing edge). Runs are never closer than wait, the last call always runs, and a single call runs exactly once. The schedule check pins the exact times: calls every 10 ms with wait = 50 run at 0, 50, 100 and 150 ms.
// Leading and trailing: the first call runs at once, and if more calls arrive inside the window,// the last of them runs when the window ends, so the final value (scroll position, input) isn't lost.function throttle(fn, wait) {let last = -Infinity;let timer = null;let pendingArgs = null;let pendingThis = null;const invoke = () => {last = Date.now();const args = pendingArgs, self = pendingThis;pendingArgs = pendingThis = null;fn.apply(self, args);};return function (...args) {pendingArgs = args; // always the latest callpendingThis = this;const remaining = wait - (Date.now() - last);if (remaining <= 0) {if (timer) {clearTimeout(timer);timer = null;}invoke();} else if (!timer) {timer = setTimeout(() => {timer = null;invoke();}, remaining);}};}
passes 5 checks run on every build, against the native method where there is one
- leading run, then the last call of each window
- runs are never closer than wait
- the final value is never lost
- a single call runs once, with no trailing repeat
- trailing call keeps the latest this
leading: false never runs immediately: each new window waits the full wait, then runs the latest call. trailing: false is the basic gate. cancel() forgets the pending call and resets the window (for unmount), and flush() runs the pending call now (before navigating away). For visual updates the right interval is often one frame: rafThrottle uses requestAnimationFrame, so the handler runs once per painted frame with the latest event.
// lodash's options and controls: leading / trailing edges, cancel and flush. Plus a frame-based// throttle for scroll and pointer handlers that only need to run once per painted frame.function throttle(fn, wait, { leading = true, trailing = true } = {}) {let last = -Infinity;let timer = null;let pendingArgs = null;let pendingThis = null;const invoke = () => {last = Date.now();const args = pendingArgs, self = pendingThis;pendingArgs = pendingThis = null;fn.apply(self, args);};// Only ever scheduled by a call inside a window, so there is always a pending call to run.const trailingEdge = () => {timer = null;invoke();};function throttled(...args) {pendingArgs = args;pendingThis = this;const remaining = wait - (Date.now() - last);if (remaining <= 0 && leading) {if (timer) {clearTimeout(timer);timer = null;}invoke();} else if (!timer && trailing) {// With leading: false a new window starts here, so the call waits a full `wait`.timer = setTimeout(trailingEdge, remaining > 0 ? remaining : wait);}}throttled.cancel = () => {clearTimeout(timer);timer = null;pendingArgs = pendingThis = null;last = -Infinity;};throttled.flush = () => {if (timer) {clearTimeout(timer);trailingEdge();}};return throttled;}function rafThrottle(fn) {let frame = null;let args, self;function throttled(...a) {args = a;self = this;if (frame === null) {frame = requestAnimationFrame(() => {frame = null;fn.apply(self, args);});}}throttled.cancel = () => {if (frame !== null) cancelAnimationFrame(frame);frame = null;};return throttled;}
passes 6 checks run on every build, against the native method where there is one
- defaults behave like the intermediate version
- leading: false waits a full window, even after a long pause
- trailing: false drops calls inside the window
- cancel drops the pending call and resets the window
- flush runs the pending call now
- rafThrottle: one run per frame with the latest arguments
Scroll and resize handlers
Scroll and pointer events can fire many times per frame. Throttling (or a frame-based throttle) keeps work like position-based UI updates to a steady rate.
lodash.throttle
The library version defaults to both edges and adds cancel and flush, the API of the advanced stage. It's built on its debounce with a maxWait.
Throttle vs debounce
Throttle runs regularly while events keep coming (progress, scroll position). Debounce waits for them to stop (search as you type, autosave).
Arrow functions or
fn(...args)instead offn.apply(this, args), which losesthis.Dropping the final call, so the UI ends one update behind.
Starting a new timer on every call, which turns the throttle into a debounce or runs more often than
wait.A trailing run that repeats a single call (run twice for one event).
Never cancelling a pending trailing call when a component unmounts.
How is throttle different from debounce?
Debounce resets its timer on every call and runs once after calls stop. Throttle guarantees a run at most every wait ms while calls continue, so a steady stream of events still produces regular updates.
How would you use it in React?
Create the throttled function once (useMemo or a ref) so every render doesn't make a new one with a fresh window, keep the latest callback in a ref, and call cancel() in an effect cleanup.
Why might requestAnimationFrame beat a 16 ms throttle?
It's aligned with the display's actual refresh (60, 120 Hz…) and pauses in background tabs, while a timer drifts and keeps firing.