What is throttle?

Throttling limits a function to run at most once per time interval, no matter how often it is triggered; unlike debounce, it keeps running regularly during a continuous stream of events.

How it behaves

The first call runs (leading edge). Further calls within the interval are ignored or, in many implementations, the latest one is remembered and run when the interval ends (trailing edge), so the final state is never lost.

Typical uses

  • Scroll handlers (infinite scroll checks, sticky headers, scroll progress).
  • Mouse or pointer move tracking, drag and drop.
  • Window resize when you want live updates, not just the final size.
  • Rate-limiting button presses or API calls in games and editors.
  • Sending analytics or presence updates at a steady rate.

Leading and trailing

  • Leading: respond instantly to the first event.
  • Trailing: also run once after the last event, with the latest arguments, so the UI ends in the correct state.

Alternatives

For visual updates tied to scrolling or animation, requestAnimationFrame is a natural throttle: it runs at most once per frame, in sync with painting. For "is this element visible?" checks, IntersectionObserver removes the need for scroll handlers entirely.

Throttle vs debounce

Throttle = "steady drip while events continue"; debounce = "one call after the storm".

Code example

js
1function throttle(fn, interval) {
2 let last = 0;
3 let trailingTimer = null;
4 let lastArgs = null;
5 return function (...args) {
6 const now = Date.now();
7 const remaining = interval - (now - last);
8 lastArgs = args;
9 if (remaining <= 0) {
10 clearTimeout(trailingTimer);
11 trailingTimer = null;
12 last = now;
13 fn.apply(this, args); // leading edge
14 } else if (!trailingTimer) {
15 trailingTimer = setTimeout(() => {
16 last = Date.now();
17 trailingTimer = null;
18 fn.apply(this, lastArgs); // trailing edge with the latest args
19 }, remaining);
20 }
21 };
22}
23
24const calls = [];
25const onScroll = throttle((y) => calls.push(y), 50);
26
27// 20 "scroll events", 10ms apart (200ms total)
28for (let i = 0; i < 20; i++) setTimeout(() => onScroll(i * 10), i * 10);
29
30await new Promise((r) => setTimeout(r, 350));
31console.log("events: 20, handler runs:", calls.length); // about 4-5 runs, not 20
32console.log("last position handled:", calls.at(-1)); // 190 - the final position is never lost

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