JavaScriptMedium
Implement a throttle function
A throttle wrapper remembers when it last ran; it runs immediately if at least interval ms have passed (leading edge) and otherwise schedules one trailing call with the latest arguments for when the interval ends, so it fires at a steady rate without dropping the final state.
Requirements to cover
- Leading call: respond immediately to the first event.
- At most once per interval while calls keep coming.
- Trailing call with the latest arguments, so the final position or value is never lost.
- Preserve
thisand arguments. - Options
{ leading, trailing }to turn each edge off (Lodash-compatible). cancel()to clear the pending trailing call.
Timestamp vs timer implementations
- Timestamp-only: simple, leading edge only, can drop the last event.
- Timer-only: trailing edge only, adds latency to the first event.
- Combined (below): leading and trailing, the most useful in UIs.
Alternatives
requestAnimationFrame-based throttling for visual updates (once per frame).IntersectionObserverinstead of throttled scroll handlers for visibility checks.
Testing
Use fake timers and assert both the number of calls and the arguments of the last one.
Code example
js
1function throttle(fn, interval, { leading = true, trailing = true } = {}) {2 let lastRun = 0;3 let timer = null;4 let pendingArgs = null;5 let pendingThis = null;67 const run = (ctx, args) => {8 lastRun = Date.now();9 fn.apply(ctx, args);10 };1112 function throttled(...args) {13 const now = Date.now();14 if (!lastRun && !leading) lastRun = now; // skip the leading edge15 const remaining = interval - (now - lastRun);1617 if (remaining <= 0) {18 clearTimeout(timer);19 timer = null;20 run(this, args);21 } else if (trailing) {22 pendingArgs = args; // always keep the latest23 pendingThis = this;24 timer ??= setTimeout(() => {25 timer = null;26 run(pendingThis, pendingArgs);27 }, remaining);28 }29 }30 throttled.cancel = () => {31 clearTimeout(timer);32 timer = null;33 lastRun = 0;34 };35 return throttled;36}3738const positions = [];39const onScroll = throttle((y) => positions.push(y), 100);4041// 30 scroll events over ~300ms42for (let i = 0; i <= 30; i++) setTimeout(() => onScroll(i * 10), i * 10);43await new Promise((r) => setTimeout(r, 450));4445console.log(positions[0]); // 0 - leading edge: immediate46console.log(positions.length <= 5); // true - throttled to ~1 per 100ms47console.log(positions.at(-1)); // 300 - trailing edge keeps the final position4849// Trailing only (e.g. send the final drag position after each interval)50const trailingOnly = [];51const onDrag = throttle((x) => trailingOnly.push(x), 50, { leading: false });52onDrag(1);53onDrag(2);54onDrag(3);55await new Promise((r) => setTimeout(r, 80));56console.log(trailingOnly); // [3]
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.