Sub topic 1
Why Some Events Fire Too Often
Prerequisites
This chapter assumes you know JavaScript functions and arrow functions, closures, setTimeout and clearTimeout, DOM event listeners, and rest parameters with Function.prototype.apply.
Why Some Events Fire Too Often
Some browser events fire many times per second. input fires on every keystroke. scroll, resize, and pointermove can fire dozens of times per second. If each event triggers a network request or a layout recalculation, the page slows down and your server receives requests it doesn't need.
Debouncing is a technique that delays a handler until events stop arriving for a set time. Throttling, covered in the next chapter, runs a handler at most once per time interval.
The Building Blocks: Closures, setTimeout, and clearTimeout
A debounce function needs a timer ID that stays alive between calls. A closure provides this. The returned function keeps access to the timerId variable declared in the outer function. setTimeout schedules work and returns an ID, and clearTimeout cancels that work using the ID.
Building a Debounce Function
Each call cancels the pending timer and starts a new one. The wrapped function runs only after wait milliseconds pass with no new calls. Because it runs at the end of a burst, this version is called a trailing-edge debounce.
function debounce(fn, wait) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, args);
}, wait);
};
}
const input = document.querySelector('#search');
input.addEventListener('input', debounce((event) => {
console.log('Search for:', event.target.value);
}, 300));Keeping this and Arguments Intact
Two details make the wrapper behave like the original handler:
...argscollects every argument, including theeventobject, so the handler receives it.- The arrow function inside
setTimeouthas nothisof its own. It uses thethisof the returned function, which the DOM sets to the element.fn.apply(this, args)passes both along.
A common mistake is to write debounce(handler, 300) inside another function that runs on every event. Each call creates a new closure with its own timer, so nothing gets debounced. Create the debounced function once, then reuse it.
Exercise
A user types "cat" quickly, then pauses for 500 ms. With a 300 ms trailing debounce, how many times does the handler run, and what value does it log?
Show answer
It runs once, about 300 ms after the "t" keystroke, and logs "cat" because each earlier keystroke reset the timer.
Exercise
Why does calling clearTimeout(timerId) on the very first call not cause an error?
Show answer
On the first call timerId is undefined, and clearTimeout ignores IDs that don't refer to an active timer, so the call does nothing.