Chapter XXIV · Advanced Concepts
Debouncing
Debouncing ensures a function is only executed after a specified pause period has elapsed since its last invocation.
01 How It Works
Think of an elevator door timer that resets its close countdown every time someone new steps inside.
Every new trigger resets the internal timer delay, delaying execution until typing or scrolling activity stops.
example.js
function debounce(fn, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn.apply(this, args), delay);
};
}
window.addEventListener('resize', debounce(() => console.log("Resized!"), 300));
1. Wrap target function inside a debouncing wrapper.
2. Clear existing active timers on every new event trigger.
3. Set a new timeout delay to execute the function once activity settles.
02 Practical Example
Here is how you might see this concept applied in real-world code:
practical.js
const searchInput = document.getElementById("search");
searchInput.addEventListener("input", debounce(e => {
console.log("Fetching query:", e.target.value);
}, 500));
Key Takeaway
Debouncing prevents excessive function executions during rapid-fire events like typing or resizing.