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 also be comfortable with closures, setTimeout, clearTimeout, and Function.prototype.apply.
The Problem with Dropping Calls
The timestamp throttle runs the handler at most once per wait window and discards every call in between. During a long scroll that works well. When the scroll stops, it can cause a bug. Suppose the user's last scroll event lands 50 ms after the handler last ran. With a 200 ms window, that event is dropped, and no later event arrives to replace it. Your UI then shows the scroll position from 50 ms before the user stopped, and it stays that way.
A trailing call fixes this. A call that arrives inside the window is no longer thrown away. The throttle records it and schedules one run for the end of the window, using the most recent arguments. The final state of every burst then always reaches the handler.
The Working Model
Each call computes remaining, the time left in the current window:
- If
remaining <= 0, the window is over. Run now and start a new window. - If not, save
thisand the arguments as the pending call. If no timer is scheduled, schedule one for when the window ends. If a timer already exists, leave it alone, because it will pick up the newer saved arguments when it fires.
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);
}
}
};
}
// Demo for Node or the browser console
const log = throttle((n) => console.log('ran with', n), 200);
let i = 0;
const id = setInterval(() => {
log(++i);
if (i === 7) clearInterval(id);
}, 50);
// Logs: ran with 1, ran with 4 or 5, ran with 7The output proves the fix. Call 7 is the last one, and it still runs once its window closes.
Details That Matter
- Setting
lastwhen the timer fires. The trailing run starts a new window. Iflastkept its old value, a call arriving just after the trailing run would also run immediately, and the handler would run twice in quick succession. - The
clearTimeoutin the immediate branch. Timers can fire late when the main thread is busy. If a call findsremaining <= 0while a timer is still pending, the call runs now and cancels the stale timer, which would otherwise repeat the work. - Only one timer at a time. Rescheduling on every call would turn this into a debounce, and the trailing run would keep moving later. The
timerId === undefinedcheck keeps the end of the window fixed.
Common Errors
| Mistake | Symptom |
|---|---|
| Storing the arguments only when the timer is created | The trailing call uses stale data from early in the burst |
| Not resetting `timerId` inside the callback | No trailing call is ever scheduled again |
| Using `fn(...args)` in an arrow function without saving `this` | Methods lose their receiver in the trailing call |
Exercise
With wait = 200, the throttled function is called at 0 ms with "a", at 50 ms with "b", and at 120 ms with "c". When does fn run, and with which arguments?
Show answer
It runs twice. At 0 ms it runs immediately with "a" because remaining is negative (last starts at 0 and the clock is far past it). At 50 ms, remaining is 150, so "b" is saved and a timer is set for 200 ms. At 120 ms, "c" replaces "b" as the pending argument and no new timer is created. At 200 ms the timer fires and fn runs with "c".
Exercise
What goes wrong if you remove the if (timerId === undefined) check and schedule a new timer on every call inside the window?
Show answer
Each call creates another timer without clearing the old one, so the handler runs several times near the end of the window, once per buffered call. All of those runs use the latest pending arguments. The handler is no longer limited to one run per window.