JAVASCRIPT
Debouncing DOM Events for Performance and Efficiency
Implement a debounce utility to limit the rate at which an event handler fires, preventing excessive function calls during rapid user interactions like typing or resizing.
function debounce(func, delay) {
let timeoutId;
return function(...args) {
const context = this;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(context, args), delay);
};
}
// Example Usage with a DOM event:
// <input type="text" id="myInput" placeholder="Type here...">
// <p>You typed: <span id="output"></span></p>
// const myInput = document.getElementById('myInput');
// const output = document.getElementById('output');
// function handleInputChange(event) {
// // This function will only execute after a pause in typing
// console.log('Input changed (debounced):', event.target.value);
// output.textContent = event.target.value;
// }
// const debouncedHandleInputChange = debounce(handleInputChange, 500); // 500ms delay
// myInput.addEventListener('input', debouncedHandleInputChange);
// Another example for window resize:
// let resizeCount = 0;
// function handleWindowResize() {
// resizeCount++;
// console.log('Window resized (debounced):', resizeCount);
// // Perform expensive layout calculations here
// }
// const debouncedHandleWindowResize = debounce(handleWindowResize, 200);
// window.addEventListener('resize', debouncedHandleWindowResize);
How it works: Debouncing is a technique to control how often a function is executed, especially useful for event handlers that might fire rapidly (e.g., `input`, `scroll`, `resize`). This `debounce` function creates a wrapper that delays the execution of the original function until a specified `delay` has passed without any new events triggering it. This prevents unnecessary resource consumption and improves performance by consolidating multiple rapid events into a single execution.