Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I debounce an event handler to improve performance?
Asked on Mar 04, 2026
Answer
Debouncing is a technique to limit the rate at which a function is executed, especially useful for performance optimization in event handlers. Here's a simple implementation of a debounce function in JavaScript.
<!-- BEGIN COPY / PASTE -->
function debounce(func, delay) {
let timeoutId;
return function(...args) {
if (timeoutId) clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
const handleResize = () => {
console.log("Window resized");
};
window.addEventListener("resize", debounce(handleResize, 300));
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "debounce" function takes two arguments: the function to debounce ("func") and the delay in milliseconds ("delay").
- It returns a new function that clears the previous timeout if it exists and sets a new one.
- In the example, the "handleResize" function is debounced with a delay of 300 milliseconds.
- The "resize" event listener on the "window" object uses the debounced function, reducing the number of times "handleResize" is called during rapid resizing.
Recommended Links:
