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

  1. Leading call: respond immediately to the first event.
  2. At most once per interval while calls keep coming.
  3. Trailing call with the latest arguments, so the final position or value is never lost.
  4. Preserve this and arguments.
  5. Options { leading, trailing } to turn each edge off (Lodash-compatible).
  6. 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).
  • IntersectionObserver instead 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;
6
7 const run = (ctx, args) => {
8 lastRun = Date.now();
9 fn.apply(ctx, args);
10 };
11
12 function throttled(...args) {
13 const now = Date.now();
14 if (!lastRun && !leading) lastRun = now; // skip the leading edge
15 const remaining = interval - (now - lastRun);
16
17 if (remaining <= 0) {
18 clearTimeout(timer);
19 timer = null;
20 run(this, args);
21 } else if (trailing) {
22 pendingArgs = args; // always keep the latest
23 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}
37
38const positions = [];
39const onScroll = throttle((y) => positions.push(y), 100);
40
41// 30 scroll events over ~300ms
42for (let i = 0; i <= 30; i++) setTimeout(() => onScroll(i * 10), i * 10);
43await new Promise((r) => setTimeout(r, 450));
44
45console.log(positions[0]); // 0 - leading edge: immediate
46console.log(positions.length <= 5); // true - throttled to ~1 per 100ms
47console.log(positions.at(-1)); // 300 - trailing edge keeps the final position
48
49// 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.

Open in study app