Sub topic 2
Building a Throttle Function
This chapter assumes you already know closures, setTimeout and clearTimeout, rest parameters with fn.apply, and the trailing-edge debounce from the previous chapter.
Building a Throttle Function
A throttle lets a handler run at most once per wait milliseconds, even while events keep firing. A timestamp check is enough to do this. The function stores the time of the last run and skips any call that comes too soon after it.
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));While scrolling continues, the handler runs about every 200 ms. The calls in between are dropped.
Debounce or Throttle? Picking the Right Tool
| Need | Technique | Example |
|---|---|---|
| React once the activity stops | Debounce | Search-as-you-type, form validation |
| Steady updates while activity continues | Throttle | Scroll position, resize layout, drag tracking |
A common mistake is to debounce a scroll handler. A debounced handler stays silent for the whole scroll, so the UI only updates after the user stops.
Leading-Edge Debounce: Fire First, Then Wait
Sometimes the first call matters most, for example on a submit button that users click twice. A leading-edge debounce runs the first call right away and then ignores further calls until wait ms pass with no new calls.
function debounceLeading(fn, wait) {
let timerId;
return function (...args) {
if (timerId === undefined) {
fn.apply(this, args);
}
clearTimeout(timerId);
timerId = setTimeout(() => {
timerId = undefined;
}, wait);
};
}Not Losing the Last Call: Trailing Throttle
The timestamp throttle has a gap. If the last event of a burst is dropped, your handler never sees the final state. The fix is to schedule one trailing call that uses the most recent this and arguments.
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);
}
}
};
}Exercise
A user scrolls for 1 second and then stops. With the simple timestamp throttle (wait 200 ms), why might the final scroll position never be logged, and which version fixes this?
Show answer
The last scroll event may arrive less than 200 ms after the previous run, so it is dropped and nothing runs later. The trailing throttle fixes this because it schedules one more call with the latest arguments once the remaining time has passed.
Exercise
Should a "Save" button that users tend to double-click use a trailing debounce or a leading-edge debounce?
Show answer
A leading-edge debounce. It saves on the first click right away and ignores the duplicate clicks that follow within the wait period.