Implementing Debounce and Throttle Functions in JavaScript
Debounce Function
A debounce function delays the execution of a callback until after a specified waiting period has elapsed since the last time the function was invoked. This is useful for events that fire rapidly, such as window resizing or keyboard input, where you want to perform a action only after the user has stoped triggering the event.
function debounce(callback, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
callback.apply(this, args);
}, delay);
};
}
function handleInput() {
console.log('Processing input...');
}
const inputElement = document.querySelector('input');
inputElement.addEventListener('input', debounce(handleInput, 300));
Throttle Functon
A throttle function ensures a callback is executed at most once per specified time interval. It's ideal for limiting the rate of execution during continuous events like scrolling or mouse movement.
function throttle(callback, interval) {
let isThrottled = false;
return function(...args) {
if (isThrottled) return;
isThrottled = true;
setTimeout(() => {
callback.apply(this, args);
isThrottled = false;
}, interval);
};
}
function handleScroll() {
console.log('Handling scroll event.');
}
window.addEventListener('scroll', throttle(handleScroll, 200));