What is the difference between throttling and debouncing techniques in event handling in JavaScript?
sobes.tech AI
Answer from AI
Throttling and debouncing are techniques for controlling the frequency of function calls when handling events in JavaScript to avoid excessive calls.
-
Debouncing delays the execution of a function until the event stops firing for a certain period. If the event occurs again, the timer resets. This is useful, for example, when processing user input, so the function only triggers after the user has finished typing.
-
Throttling limits the invocation of a function to no more than a specified interval. The function will be called regularly but not more often than the set interval, even if the event occurs more frequently. This is convenient for scroll or resize events to ensure the function runs at a consistent rate.
Example of debouncing:
function debounce(func, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, args), delay);
};
}
window.addEventListener('resize', debounce(() => {
console.log('Resize event handled after user stops resizing');
}, 300));
Example of throttling:
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('Scroll event handled at most once every 200ms');
}, 200));