To reduce performance issues in user interactions (e.g., scroll
and resize
events), we use debouncing
and throttling
techniques.
Debouncing: Runs a function only after a specified time has passed since the last event. For example, the function executes only after the user stops resizing the window.
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
window.addEventListener('resize', debounce(() => {
console.log('Window resized');
}, 300));
Throttling: Runs a function at regular intervals, regardless of how often the event occurs. Ideal for limiting resource usage on frequently triggered events.
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
window.addEventListener('scroll', throttle(() => {
console.log('Page scrolled');
}, 300));
These techniques limit unnecessary executions and improve page performance.