When handling event listeners that trigger frequently (like scroll, resize, or keypress), executing expensive handlers on every fire can slow down the browser. Debouncing and Throttling are optimization techniques used to limit these executions.
Debouncing
Debouncing delays the execution of a function until a certain amount of time has elapsed since the last time the event fired. Useful for search input autocompletes.
function debounce(fn, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
Throttling
Throttling guarantees that a function is called at most once within a specified time window. Useful for scroll page positioning and infinite scrolls.
function throttle(fn, limit) {
let inThrottle = false;
return function(...args) {
if (!inThrottle) {
fn.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}