Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I debounce a function to limit how often it executes? Pending Review
Asked on Apr 26, 2026
Answer
Debouncing a function ensures it only executes after a specified delay has elapsed since the last time it was invoked. This is useful for optimizing performance in scenarios like handling window resizing or input events.
<!-- BEGIN COPY / PASTE -->
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
// Example usage:
const handleResize = () => {
console.log("Window resized");
};
const debouncedResize = debounce(handleResize, 300);
window.addEventListener("resize", debouncedResize);
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "debounce" function takes two parameters: the function to debounce ("func") and the delay in milliseconds ("delay").
- "clearTimeout" ensures that the previous timeout is cleared if the debounced function is called again before the delay.
- "setTimeout" is used to call the original function after the specified delay.
- "apply" is used to maintain the context ("this") and pass arguments to the original function.
- In the example, "debouncedResize" is a debounced version of "handleResize", triggered on window resize events.
Recommended Links:
