Sub topic 8
Not Losing the Last Call: Trailing Throttle
This chapter assumes you have read the earlier chapter on timestamp-based throttle. You should be comfortable with closures, setTimeout/clearTimeout, rest parameters, and Function.prototype.apply. The examples run in Node.js or a browser console.
The Problem with Dropping Calls
The timestamp throttle from the earlier chapter runs the handler only when at least wait milliseconds have passed since its last run. It ignores every call in between. During a long burst this is usually fine, because a later call soon arrives and gets through.
The trouble is at the end of the burst. Suppose a user scrolls and stops 150 ms after the last allowed run, with a 200 ms window. The final scroll event falls inside the window, so the throttle drops it. No further events arrive, so the handler never sees the final scroll position. Your "back to top" button, sticky header, or progress bar stays in the state it had partway through the scroll.
Throttle a resize handler and the same thing happens: the layout is computed for a width the window no longer has. A plain timestamp throttle is lossy at the end of a burst. Most UI work cares more about the final state than about any intermediate one.
A trailing call fixes this. When a call arrives during the cooldown, the throttle remembers it and schedules one run for the moment the cooldown ends. That run uses the most recent this and arguments.
The Implementation
function throttle(fn, wait) {
let last = 0;
let timerId;
let pendingThis;
let pendingArgs;
return function (...args) {
const now = Date.now();
const remaining = wait - (now - last);
if (remaining <= 0) {
clearTimeout(timerId);
timerId = undefined;
last = now;
fn.apply(this, args);
} else {
pendingThis = this;
pendingArgs = args;
if (timerId === undefined) {
timerId = setTimeout(() => {
last = Date.now();
timerId = undefined;
fn.apply(pendingThis, pendingArgs);
}, remaining);
}
}
};
}The closure holds four pieces of state:
| Variable | Meaning |
|---|---|
| `last` | Timestamp of the most recent run of `fn`, whether immediate or trailing |
| `timerId` | ID of the scheduled trailing run, or `undefined` if none is scheduled |
| `pendingThis` | The `this` value of the most recent call made during the cooldown |
| `pendingArgs` | The arguments of the most recent call made during the cooldown |
How `remaining` drives the decision
remaining is how much of the cooldown is left. now - last is the time since the last run, so wait - (now - last) is the time until the next run is allowed.
- If
remaining <= 0, the window is open. The wrapper runsfnimmediately and recordslast = now. - If
remaining > 0, the window is closed. The wrapper stores the call's context and arguments, and makes sure exactly one timer is scheduled to fire when the window opens.
The first call always runs immediately. last starts at 0, so now - last is the full Unix timestamp, which is far larger than any realistic wait.
Overwrite the arguments, schedule the timer once
Two details work together here. Every call during the cooldown overwrites pendingThis and pendingArgs. Only the first call during the cooldown creates a timer, because the timerId === undefined guard skips scheduling while a timer is pending.
So the timer is not reset. That is the difference from debounce. A debounce timer moves back with each call. A trailing throttle timer stays fixed at the end of the current window, and the arguments it will use keep updating until it fires. The result is a guaranteed run at the window boundary with the latest data.
Why the timer sets `last = Date.now()`
The trailing run counts as a real run. If the timer did not update last, a call arriving 1 ms after the trailing run would see an old last, find remaining <= 0, and run immediately. You would get two runs 1 ms apart, which breaks the throttle's promise. Setting last inside the timer callback keeps every pair of runs at least wait apart.
The callback uses Date.now() rather than the now captured when the timer was scheduled, because timers fire late when the event loop is busy. The actual firing time is what matters.
Why the immediate branch clears the timer
At first it seems impossible for the immediate branch to run while a timer is pending. The timer was scheduled to fire exactly when remaining reaches zero. But setTimeout guarantees only a minimum delay. If the main thread is busy, for example with a long task or a heavy event handler, a new call can arrive after the window has opened but before the timer callback has run.
That call takes the immediate branch. Without clearTimeout(timerId), the stale timer would fire a moment later with older arguments, and you would get two runs back to back, the second one using older data. Clearing the timer and resetting timerId makes the fresh immediate call replace the pending trailing call.
Seeing the Difference
This script sends ten calls, 60 ms apart, through a 200 ms trailing throttle. It runs in Node.js as shown.
function throttle(fn, wait) {
let last = 0;
let timerId;
let pendingThis;
let pendingArgs;
return function (...args) {
const now = Date.now();
const remaining = wait - (now - last);
if (remaining <= 0) {
clearTimeout(timerId);
timerId = undefined;
last = now;
fn.apply(this, args);
} else {
pendingThis = this;
pendingArgs = args;
if (timerId === undefined) {
timerId = setTimeout(() => {
last = Date.now();
timerId = undefined;
fn.apply(pendingThis, pendingArgs);
}, remaining);
}
}
};
}
const start = Date.now();
const report = throttle((n) => {
console.log(`ran with call ${n} at ~${Date.now() - start} ms`);
}, 200);
let n = 0;
const intervalId = setInterval(() => {
n += 1;
report(n);
if (n === 10) clearInterval(intervalId);
}, 60);Typical output, with a few milliseconds of jitter:
ran with call 1 at ~60 ms
ran with call 4 at ~260 ms
ran with call 7 at ~460 ms
ran with call 10 at ~660 msCall 1 runs immediately. Calls 2 and 3 arrive in the cooldown. Call 2 schedules a timer for 260 ms. Call 4 arrives at 240 ms and overwrites the pending arguments, so the timer runs with 4. The pattern repeats, and the final call, 10, is handled at 660 ms, 60 ms after the burst ended.
The timestamp-only throttle, given the same input, runs calls 1 (60 ms), 5 (300 ms), and 9 (540 ms). Call 10 is dropped, so the handler never sees the final value. The runs are also spaced less evenly, because they depend on when calls happen to land rather than on the window boundaries.
| Behavior | Timestamp throttle | Trailing throttle |
|---|---|---|
| First call in a burst | Runs immediately | Runs immediately |
| Calls during cooldown | Dropped | Latest one is kept |
| Final call of a burst | Often dropped | Always handled, within `wait` ms |
| Runs per 1 s of steady input, `wait` = 200 | Up to 5, unevenly spaced | Up to 5, near window boundaries |
| Uses a timer | No | Yes, at most one at a time |
| Can run after input stops | No | Yes, once |
Gotchas and Edge Cases
The trailing run happens after the caller has moved on
The trailing call runs asynchronously, up to wait ms after the last input. By then the DOM node may be gone, a React component may have unmounted, or a test may have finished. The handler runs anyway. Code that touches removed elements or updates unmounted state can throw or log warnings. The fix is a cancel method, which the next chapter adds.
Return values are lost
The wrapper returns undefined. Immediate runs could return fn's result, but trailing runs happen inside a timer and have no caller to return to. Treat throttled functions as fire-and-forget. If you need a result, have fn write it somewhere, such as state, a variable, or a callback.
Stale references stay in memory
pendingThis and pendingArgs keep their values after the trailing run. If the arguments are large objects or DOM events that reference detached nodes, the closure keeps them alive until the next call during a cooldown overwrites them. For long-lived throttled functions that handle heavy data, set both to undefined after invoking fn in the timer callback.
Errors inside `fn`
The timer callback resets timerId before calling fn. That order matters. If fn throws, the throttle is already back in a consistent state and the next call behaves normally. If you reorder those lines, an exception would leave timerId set to a timer that has already fired, and no trailing call would ever be scheduled again.
Clock changes
Date.now() follows the system clock, which can jump when the user changes the time or NTP adjusts it. If the clock jumps backward, now - last goes negative and remaining can exceed wait, delaying runs. In browsers and modern Node.js, performance.now() is monotonic and avoids this. Swap it in if your throttled work is long-running or timing-sensitive.
Exercise
With the trailing throttle above and wait = 200, a single call arrives at t = 0 and no other calls follow. How many times does fn run, and when? Then a second call arrives at t = 50 and nothing after it. What changes?
Show answer
With one call, fn runs once at t = 0. The call takes the immediate branch, and no timer is scheduled because no call arrived during the cooldown. With the extra call at t = 50, that call finds remaining = 150, stores its arguments, and schedules a timer. fn runs twice: at t = 0 with the first call's arguments and at about t = 200 with the second call's arguments.
Exercise
A developer removes the line last = Date.now(); from the timer callback. Calls arrive at t = 0, t = 100, and t = 210, with wait = 200. Trace the runs and explain what breaks.
Show answer
t = 0 runs immediately and sets last = 0. t = 100 schedules a trailing run, which fires at t = 200 but leaves last at 0. At t = 210, remaining = 200 - 210 = -10, so the call runs immediately. fn runs at 200 and again at 210, only 10 ms apart, which breaks the rule that runs are at least wait apart. Updating last in the timer callback prevents this.
Exercise
Modify the trailing throttle so that pendingThis and pendingArgs do not keep references alive after the trailing run, without changing which arguments fn receives.
Show answer
In the timer callback, copy the values to locals, clear the shared variables, then call fn: const ctx = pendingThis; const args = pendingArgs; pendingThis = undefined; pendingArgs = undefined; last = Date.now(); timerId = undefined; fn.apply(ctx, args);. Copying first ensures fn still receives the latest context and arguments. Clearing before the call also keeps the state clean if fn throws.