Sub topic 7
Leading-Edge Debounce: Fire First, Then Wait
This chapter assumes you have already built the trailing-edge debounce from earlier in the tutorial. You should also be comfortable with closures, setTimeout/clearTimeout, and fn.apply(this, args).
A trailing-edge debounce waits for a burst of calls to end before it runs anything. That suits search-as-you-type, but some actions should run right away. A "Submit" button that a user double-clicks should submit at once, and the second click should be ignored. A leading-edge debounce gives you that: it runs on the first call of a burst, then ignores further calls until the input goes quiet for wait milliseconds.
The working model
A leading-edge debounce keeps one piece of state, the timer ID, and it uses that ID as a flag:
timerId === undefinedmeans no burst is in progress. The next call runs immediately.timerIdholds a value while a burst is in progress. Calls are ignored.- Every call restarts the timer. When the timer finally fires, it clears
timerId, which ends the burst.
The timer never calls fn. Its only job is to mark the end of the quiet period.
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);
};
}
const start = Date.now();
const log = debounceLeading((label) => {
console.log('ran:', label, 'at', Date.now() - start, 'ms');
}, 200);
log('a'); // runs: no burst in progress
setTimeout(() => log('b'), 100); // ignored, quiet period now ends at 300
setTimeout(() => log('c'), 250); // ignored, quiet period now ends at 450
setTimeout(() => log('d'), 500); // runs: the burst ended at 450Run it with Node and you should see roughly:
ran: a at 0 ms
ran: d at 500 msCalls b and c came less than 200 ms after the previous call, so each one extended the burst. Call d arrived after 250 ms of silence, so it started a new burst and ran immediately.
Common errors
| Mistake | Symptom |
|---|---|
| The timer callback never sets `timerId = undefined` | `fn` runs once and then never again |
| Starting the timer only when `fn` runs, without restarting it on ignored calls | You get a throttle: `fn` runs again every `wait` ms during a long burst |
| Checking `if (!timerId)` | Works in browsers, but it is fragile if an environment returns `0` as an ID. `=== undefined` states the intent |
| Expecting the last call's arguments to be used | Leading debounce keeps the **first** call's arguments and drops the rest |
When to choose it
Use leading-edge debounce when the first event carries the user's intent and later events in the burst are noise:
- Preventing double submission from repeated clicks or Enter key presses.
- Showing feedback right away, such as opening a menu or playing a sound, without repeating it while the user keeps triggering it.
- Starting a "user is typing" indicator on the first keystroke.
Because every call restarts the timer, someone who clicks steadily every 150 ms with wait set to 200 ms will get exactly one run, however long they keep clicking. If you need a guaranteed run every wait ms during continuous input, use a throttle instead.
Exercise
In the demo above, suppose the fourth call happens at 400 ms instead of 500 ms. What is printed, and why?
Show answer
Only "ran: a at 0 ms". Call c at 250 ms restarted the timer to fire at 450 ms, so at 400 ms timerId is still set and the call is ignored. It also restarts the timer, pushing the end of the burst to 600 ms.
Exercise
A teammate removes the line timerId = undefined; from the timer callback. Describe the new behavior.
Show answer
After the first call, timerId always holds a timer ID, even after that timer has fired, so the check timerId === undefined is never true again. The wrapped function runs exactly once for the lifetime of the debounced function.