Understanding Debounce and Throttle in JavaScript
When dealing with events that fire frequently, such as window resizing or keyboard input, executing heavy operations on every event can severely impact performance. Two common techniques to control the execution rate of functions are debouncing and throttling.
Debounce
Debouncing ensures that a function is only executed after a specified period of inactivity. If the event is triggered again before the delay period ends, the timer resets. This means the event handler will only execute once within a given time limit, specifically after the user has stopped triggering the event for the defined duration.
javascript function createDebouncedTask(callback, delayMs) { let pendingTimer = null;
return function(...params) {
if (pendingTimer) {
clearTimeout(pendingTimer);
}
const currentContext = this;
pendingTimer = setTimeout(() => {
callback.apply(currentContext, params);
pendingTimer = null;
}, delayMs);
};
}
// Usage Example: const handleDebouncedInput = createDebouncedTask(() => { console.log('Debounce successful!'); }, 500);
const debounceInputElement = document.getElementById('debounce'); debounceInputElement.addEventListener('input', handleDebouncedInput);
Throttle
Throttling ensures that a function executes at most once within a specified time period. If a event is triggered continuously in a short amount of time, the function will run once, and then become inactive for the remaining duration of the time limit. It only becomes eligible to run again once the cooling period has elapsed.
javascript function createThrottledTask(callback, intervalMs) { let isWaiting = false;
return function(...params) {
if (!isWaiting) {
const currentContext = this;
isWaiting = true;
setTimeout(() => {
callback.apply(currentContext, params);
isWaiting = false;
}, intervalMs);
}
};
}
// Usage Example: const handleThrottledInput = createThrottledTask(() => { console.log('Throttle successful!'); }, 500);
const throttleInputElement = document.getElementById('throttle'); throttleInputElement.addEventListener('input', handleThrottledInput);