Sub topic 5
Building a Throttle Function
This chapter assumes you are comfortable with closures, setTimeout, rest parameters, and Function.prototype.apply, and that you have read the earlier chapter on building a debounce function. Debounce waits for a pause in activity. Throttle works differently: it lets the handler run at a steady maximum rate while the activity continues. Here you will build a timestamp-based throttle, see how it behaves call by call, and work through the edge cases that make simple versions misbehave.
What Throttle Promises
A throttled function guarantees that the wrapped function runs at most once per wait milliseconds. Calls that arrive during that window are dropped. When the window closes, the next call runs right away.
Scroll handlers show why this matters. A user who scrolls for three seconds can trigger the scroll event hundreds of times. A debounced handler would do nothing until the user stopped scrolling. A throttled handler with wait = 200 runs about 15 times during those three seconds, which is often enough to update a "back to top" button or a reading-progress bar.
| Behavior during 3 seconds of continuous scrolling | Raw handler | Debounce (200 ms) | Throttle (200 ms) |
|---|---|---|---|
| Handler runs during the scroll | Every event (often 100+) | 0 | About 15 |
| Handler runs after scrolling stops | 0 extra | 1 | 0 extra |
| First event handled immediately | Yes | No | Yes |
The Timestamp Approach
The simplest throttle needs one piece of state: the time when the wrapped function last ran. On every call, compare the current time with that timestamp. If at least wait milliseconds have passed, run the function and record the new time. Otherwise, do nothing.
function throttle(fn, wait) {
let last = 0;
return function (...args) {
const now = Date.now();
if (now - last >= wait) {
last = now;
fn.apply(this, args);
}
};
}
window.addEventListener('scroll', throttle(() => {
console.log('scrollY:', window.scrollY);
}, 200));The structure follows the debounce from earlier:
lastlives in the closure, so every call to the returned function reads and writes the same value.- The returned function is a regular
function, not an arrow function, sothisis whatever the caller supplies. For a DOM listener,thisis the element. fn.apply(this, args)forwards both the context and every argument, so the handler still receives the event object.last = nowis set beforefnruns. Iffnthrows, the throttle window still starts, which prevents a failing handler from running on every single event.
No timer is involved. The throttle is a gate that checks the clock each time someone knocks.
Watching It Work
Browser events are hard to inspect precisely, so here is a Node.js script that simulates an event firing every 50 ms. Save it as throttle-demo.js and run node throttle-demo.js.
function throttle(fn, wait) {
let last = 0;
return function (...args) {
const now = Date.now();
if (now - last >= wait) {
last = now;
fn.apply(this, args);
}
};
}
const start = Date.now();
const handler = throttle((n) => {
console.log(`call ${n} ran at ~${Date.now() - start} ms`);
}, 200);
let n = 0;
const id = setInterval(() => {
n += 1;
handler(n);
if (n === 20) clearInterval(id);
}, 50);The output will be close to this (timers jitter by a few milliseconds):
call 1 ran at ~50 ms
call 5 ran at ~250 ms
call 9 ran at ~450 ms
call 13 ran at ~650 ms
call 17 ran at ~850 msTwenty calls arrived and five ran. Calls 18, 19, and 20 were dropped, and nothing ran after them. If call 20 carried the final scroll position, your UI now shows a stale value. This is the main weakness of the pure timestamp throttle, and the later chapter "Not Losing the Last Call: Trailing Throttle" fixes it.
An Alternative: The Cooldown Flag
You will also see throttle written with a boolean flag and a timer:
function throttleCooldown(fn, wait) {
let coolingDown = false;
return function (...args) {
if (coolingDown) return;
coolingDown = true;
fn.apply(this, args);
setTimeout(() => {
coolingDown = false;
}, wait);
};
}The two versions behave almost identically, but they differ in ways that matter at the edges:
| Concern | Timestamp version | Cooldown-flag version |
|---|---|---|
| Timers created | None | One per executed call |
| Accuracy of the window | Exact, measured from the clock | At least `wait`, may run late if the event loop is busy |
| Background tabs | Unaffected, since nothing is scheduled | Browsers may delay timers to 1 second or more, keeping the gate closed longer |
| Affected by system clock changes | Yes, with `Date.now()` | No |
| Easy to extend with a trailing call | Yes, `remaining = wait - elapsed` gives the delay | Needs extra state |
The timestamp version is usually the better base. It schedules nothing, so there is nothing to clean up, and it already computes the remaining time that a trailing call needs.
Edge Cases and Gotchas
The clock can move backwards
Date.now() reads the system wall clock. When the clock is corrected by NTP or changed by the user, it can jump. If it jumps backwards by an hour, now - last becomes a large negative number, and the throttle blocks every call until the clock catches up. Your scroll handler goes silent for an hour.
performance.now() is monotonic, meaning it only moves forward. It also has sub-millisecond resolution. Switching to it creates a new problem, though.
The first call can be dropped
performance.now() counts from page load (in Node.js, from process start), not from 1970. With last = 0, a call 50 ms after load with wait = 200 computes 50 - 0 = 50, which is less than 200, so the very first call is dropped. With Date.now() this never happens, because the epoch value is huge. The fix works for both clocks: start last at -Infinity, so the first call always passes.
function throttle(fn, wait) {
let last = -Infinity;
return function (...args) {
const now = performance.now();
if (now - last >= wait) {
last = now;
fn.apply(this, args);
}
};
}
const log = throttle((label) => console.log('ran:', label), 200);
log('first'); // runs, because now - (-Infinity) is Infinity
log('second'); // droppedperformance.now() is a global in browsers and in Node.js 16 and later, so this snippet runs in both.
Each wrapper has its own state
The throttle state lives in the closure created by one call to throttle. This code creates a new throttled function on every scroll event, so nothing is ever throttled:
// Broken: a fresh closure with last = 0 on every event
window.addEventListener('scroll', () => {
throttle(updateProgress, 200)();
});Create the throttled function once and keep the reference. You also need that same reference to call removeEventListener later. The React chapter covers the same issue across re-renders.
Return values are discarded
The throttled function returns undefined, even when fn returns something. If callers need a result, store it in the closure and return the most recent value:
function throttle(fn, wait) {
let last = -Infinity;
let result;
return function (...args) {
const now = Date.now();
if (now - last >= wait) {
last = now;
result = fn.apply(this, args);
}
return result;
};
}Dropped calls then return the previous result. This matches Lodash, but it can confuse callers who expect a fresh value, so add it only when you need it.
`wait` of zero or less
With wait <= 0, the condition now - last >= wait is always true, so every call runs. That is a reasonable "throttling disabled" mode, but validate the argument if a misconfigured wait would hide a performance problem.
Common Errors Recap
- Using an arrow function as the returned wrapper, which loses the caller's
this. - Calling
fn(...args)instead offn.apply(this, args), which also losesthis. - Initializing
lastto0while usingperformance.now(), which drops the first call. - Creating the throttled function inside the event handler, which disables throttling.
- Expecting the last event of a burst to be handled by a pure timestamp throttle.
Exercise
A timestamp throttle with wait = 100 uses Date.now() and starts with last = 0. Calls arrive at t = 0, 30, 90, 100, 150, 210, and 230 ms (t measured from the first call). Which calls run?
Show answer
The calls at 0, 100, and 210 run. The call at 0 runs because Date.now() minus 0 is huge, and it sets last to 0. The calls at 30 and 90 are dropped because less than 100 ms have passed. The call at 100 runs because 100 - 0 >= 100, and it sets last to 100. The call at 150 is dropped. The call at 210 runs because 210 - 100 = 110, and it sets last to 210. The call at 230 is dropped and is never handled.
Exercise
You change the timestamp throttle to use performance.now() but keep last = 0. A button click handler throttled with wait = 1000 sometimes ignores the first click right after page load. Explain why and give the fix.
Show answer
performance.now() counts from page load, so a click 400 ms after load computes 400 - 0 = 400, which is less than 1000, and the call is dropped. Initialize last to -Infinity so the first comparison is always Infinity >= wait and the first call always runs.
Exercise
Why does the timestamp throttle set last = now before calling fn.apply(this, args) instead of after?
Show answer
If fn throws, code after the call never runs. Setting last first means the throttle window starts even when the handler fails, so a broken handler runs at most once per wait instead of on every event. It also records the time the call was accepted, not the time fn finished, so a slow fn does not stretch the window.