Sub topic 7
Leading-Edge Debounce: Fire First, Then Wait
The trailing-edge debounce you built earlier waits for a burst of calls to end, then runs the handler once. That works well for search boxes, where you want the final value. Other cases need the opposite. When a user clicks a "Submit" button, the first click should work right away. The extra clicks that follow it should do nothing. A leading-edge debounce gives you that behavior: it runs on the first call of a burst and ignores the rest until the calls stop for wait milliseconds.
This chapter assumes you already know closures, setTimeout and clearTimeout, rest parameters with fn.apply, and the trailing-edge debounce from the earlier chapters. It also assumes you know why the wrapper must pass on this and the arguments.
What "Leading Edge" Means
Picture a burst of calls as a block on a timeline. The leading edge is the moment the block starts, and the trailing edge is the moment it ends, once wait milliseconds pass with no new calls. The two kinds of debounce differ only in which edge runs the handler.
| Behavior | Trailing-edge debounce | Leading-edge debounce |
|---|---|---|
| When the handler runs | `wait` ms after the last call | Immediately on the first call |
| Which arguments it sees | The last call's | The first call's |
| Delay felt by the user | At least `wait` ms | None |
| Typical use | Search-as-you-type, autosave, resize layout | Submit buttons, "like" toggles, keyboard shortcuts |
| Can return the handler's result synchronously | No | Yes, for the call that runs |
Both kinds treat a burst the same way. A burst lasts as long as calls keep arriving less than wait ms apart. Each new call extends it.
The Implementation
function debounceLeading(fn, wait) {
let timerId;
return function (...args) {
if (timerId === undefined) {
fn.apply(this, args);
}
clearTimeout(timerId);
timerId = setTimeout(() => {
timerId = undefined;
}, wait);
};
}Here timerId has two jobs. It is the handle for the pending timeout, and it also tells you which state the wrapper is in:
timerId === undefinedmeans idle. No burst is in progress, so this call starts a new one and runsfn.- Any other value means the wrapper is cooling down. A burst is in progress, so the call is dropped.
Every call clears the old timer and starts a new one, whether it ran fn or not. The timer callback does no work for the user. It only sets timerId back to undefined, which ends the cooldown so the next call can fire.
The timer callback is the only code that sets timerId to undefined. If you cleared it anywhere else, for example right after fn.apply, every call would count as the start of a burst and nothing would be debounced.
Watching It Run
The script below runs in Node or a browser console. It sends a burst of four calls 30 ms apart, waits, then sends one more call.
function debounceLeading(fn, wait) {
let timerId;
return function (...args) {
if (timerId === undefined) {
fn.apply(this, args);
}
clearTimeout(timerId);
timerId = setTimeout(() => {
timerId = undefined;
}, wait);
};
}
const start = Date.now();
const report = debounceLeading((label) => {
console.log(`${Date.now() - start} ms: ran with ${label}`);
}, 100);
setTimeout(() => report('a'), 0);
setTimeout(() => report('b'), 30);
setTimeout(() => report('c'), 60);
setTimeout(() => report('d'), 90);
setTimeout(() => report('e'), 300);The output looks like this, give or take a few milliseconds of timer jitter:
0 ms: ran with a
300 ms: ran with eCall a finds the wrapper idle and runs. Calls b, c, and d arrive during the cooldown. Each one is dropped and pushes the timer's expiry out further, so the timer finally fires at 190 ms (90 + 100). By 300 ms the wrapper is idle again, so e runs.
Behaviors That Surprise People
A continuous stream fires only once
The cooldown restarts on every call, so a stream of events that never pauses for wait ms never runs the handler a second time. If you leading-debounce scroll with a 200 ms wait and the user scrolls for ten seconds without stopping, the handler runs once at the start and then stays silent. A leading-edge throttle would run every 200 ms through the same scroll.
The arguments you get are the stale ones
The handler sees only the first call's arguments. In a text input, that is the first keystroke, which is almost never the value you want. Use leading-edge debounce when every call in a burst means the same thing, as with repeated clicks on one button. Avoid it when later calls carry newer data.
Calls are dropped, not queued
The ignored calls are thrown away. A wrapper that queued them would be a rate-limited queue, which is a different tool. If dropped calls stand for real work, such as messages to send, debouncing will lose data.
An exception skips the cooldown
In the implementation above, fn.apply runs before the timer is set. If fn throws, the code after it never runs and timerId stays undefined. The next call then counts as a new burst and runs again. For a submit handler that throws partway through after it has already sent a request, a quick second click would send a duplicate. If that matters, start the cooldown before calling fn:
function debounceLeading(fn, wait) {
let timerId;
return function (...args) {
const shouldRun = timerId === undefined;
clearTimeout(timerId);
timerId = setTimeout(() => {
timerId = undefined;
}, wait);
if (shouldRun) {
return fn.apply(this, args);
}
};
}This version also returns the handler's result for the call that runs. A trailing-edge debounce cannot do that, because its handler runs later, after the caller has already returned.
Combining Leading and Trailing
Some interfaces want both: an instant response to the first event, plus one final call that uses the latest state once things settle. A "resize" handler might show an overlay right away and lay out the page again at the end. You can add both edges as options:
function debounceEdges(fn, wait, { leading = true, trailing = false } = {}) {
let timerId;
let pendingThis;
let pendingArgs;
return function (...args) {
const startsBurst = timerId === undefined;
if (startsBurst && leading) {
fn.apply(this, args);
} else {
pendingThis = this;
pendingArgs = args;
}
clearTimeout(timerId);
timerId = setTimeout(() => {
timerId = undefined;
if (trailing && pendingArgs !== undefined) {
const ctx = pendingThis;
const latest = pendingArgs;
pendingThis = undefined;
pendingArgs = undefined;
fn.apply(ctx, latest);
}
pendingThis = undefined;
pendingArgs = undefined;
}, wait);
};
}The pendingArgs !== undefined check matters. With both edges on, a single isolated call runs on the leading edge and stores nothing, so the trailing edge has nothing to do. Without the check, one click would run the handler twice. The trailing call runs only if at least one more call arrived during the cooldown. Lodash follows the same rule.
Here is what each combination of options does:
| `leading` | `trailing` | Result |
|---|---|---|
| `true` | `false` | Pure leading-edge debounce |
| `false` | `true` | Pure trailing-edge debounce |
| `true` | `true` | First call immediately, plus one final call if the burst had more than one call |
| `false` | `false` | Never runs. This is almost always a configuration bug. |
When to Reach for Leading-Edge Debounce
Use it when all three of these are true:
- The first event in a burst should get an immediate response, so the user feels no delay.
- Later events in the same burst add no new information.
- A long, unbroken stream of events should not cause repeated runs.
Double-submit protection, "copy to clipboard" buttons, and keyboard shortcuts that open a panel all fit. Search inputs, scroll position tracking, and drag handlers do not. Those need either the latest value (trailing-edge debounce) or regular updates (throttle).
Exercise
A leading-edge debounced function has wait = 100 ms. It is called at 0, 50, 120, and 250 ms. At which times does the wrapped function run, and why?
Show answer
It runs at 0 and 250 ms. The call at 0 finds the wrapper idle and runs, setting the timer to expire at 100. The call at 50 is dropped and moves the expiry to 150. The call at 120 is also dropped, because the cooldown is still active, and moves the expiry to 220. At 220 the timer fires and the wrapper becomes idle, so the call at 250 runs.
Exercise
In debounceEdges with leading and trailing both true, why does a single click run the handler only once instead of twice?
Show answer
The single call starts the burst and runs on the leading edge, so it goes through the leading branch and never sets pendingArgs. When the timer fires, pendingArgs is still undefined, and the trailing check skips the second call. A trailing call happens only if another call arrived during the cooldown.
Exercise
You wrap a scroll handler in a leading-edge debounce with wait = 200 ms to update a "back to top" button. Users report that the button only updates when they start scrolling. Explain the cause and name a better technique.
Show answer
Each scroll event restarts the 200 ms cooldown, so continuous scrolling never lets the wrapper go idle and the handler runs only on the first event. The handler needs to run regularly during the scroll, so a throttle (with a trailing call so the final position is handled) or a requestAnimationFrame-based throttle fits better.