Sub topic 5
Building a Throttle Function
This chapter assumes you know closures, setTimeout, DOM event listeners, rest parameters, and Function.prototype.apply. It also assumes you have built the trailing-edge debounce from the earlier chapter. In this chapter you build a throttle that uses a stored timestamp in place of a timer.
What throttle guarantees
Debounce waits for a burst of events to stop. Throttle runs the handler at regular intervals while the burst is still going: at most once every wait milliseconds. A scroll handler throttled to 200 ms runs about five times per second during continuous scrolling. The calls that arrive in between are dropped.
This suits events where the user needs feedback during the activity, such as updating a scroll position indicator or checking whether an element has entered the viewport.
The timestamp approach
Throttle only has to remember one value: the time of the last call that ran. When a new call arrives, it compares the current time with that value.
The implementation
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 parts work like this:
- The closure keeps
lastalive between calls. Each call tothrottlecreates its ownlast, so two throttled handlers never share state. - The returned function is a regular
function, not an arrow function. That waythisis whatever the caller supplies, such as the element when the function is used as an event listener. fn.apply(this, args)forwards the caller'sthisand all of its arguments, including the event object.- The function sets no timer. Nothing is scheduled, and a dropped call leaves nothing behind to clean up.
The first call always runs. Date.now() returns milliseconds since 1970, so now - 0 is far larger than any realistic wait. Throttle responds at the leading edge of a burst. Debounce responds only after the burst ends.
Trying it outside the browser
This script runs in Node. It calls a throttled function every 20 ms for one second.
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();
let calls = 0;
let runs = 0;
const tick = throttle(() => {
runs += 1;
console.log(`ran at ${Date.now() - start} ms`);
}, 200);
const intervalId = setInterval(() => {
calls += 1;
tick();
}, 20);
setTimeout(() => {
clearInterval(intervalId);
console.log(`${calls} calls, ${runs} runs`);
}, 1000);The script makes about 50 calls, and roughly 5 of them run, spaced about 200 ms apart.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Calling `throttle(...)` inside the handler | Every call runs, because each call creates a new `last` | Create the throttled function once and pass that function to `addEventListener` |
| Using `performance.now()` with `last = 0` | The first call may be dropped, because `performance.now()` starts near 0 | Start `last` at `-Infinity`, or use `Date.now()` |
| Using an arrow function as the wrapper | `this` inside `fn` is wrong | Return a regular `function` and use `apply` |
| Expecting the final event to be handled | The last scroll position is never logged | Add a trailing call (covered in a later chapter) |
Removing the listener
Store the throttled function in a variable if you need to remove it later. removeEventListener only matches the exact function reference you passed to addEventListener.
const onScroll = throttle(() => console.log(window.scrollY), 200);
window.addEventListener('scroll', onScroll);
// later
window.removeEventListener('scroll', onScroll);Exercise
A function is throttled with wait = 200. Calls arrive at 0, 50, 199, 200, 350, and 401 ms after the first call. Which calls run?
Show answer
The calls at 0, 200, and 401 run. The call at 0 runs and sets last. The calls at 50 and 199 are less than 200 ms after 0, so they are dropped. The call at 200 is exactly 200 ms later, which satisfies >=, so it runs. The call at 350 is only 150 ms after 200, so it is dropped. The call at 401 is 201 ms after 200, so it runs.
Exercise
A developer writes window.addEventListener('scroll', () => throttle(update, 200)()). Why does update run on every scroll event?
Show answer
Each scroll event calls throttle again, which creates a new closure with last = 0. The time check therefore passes every time. The throttled function must be created once, outside the listener.