Debouncing and Throttling
Debouncing delays execution until a burst of calls stops for a specified period. It is useful for search inputs and resize handling. Throttling limits execution to at most a certain frequency, useful for scroll or pointer events.
The correct choice depends on whether you care about the final event after a burst or continuous periodic updates.
Debounce Utility
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
const search = debounce(query => {
console.log('Searching:', query);
}, 300);💡 Each invocation resets the timer. The function executes only after calls stop arriving for the configured delay.
Key Takeaways
- Debounce waits for inactivity.
- Throttle limits execution frequency.
- Both are useful for high-frequency events.
Knowledge Check
Which technique is best suited to run a search only after the user stops typing briefly?