Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I debounce a function to limit its execution rate?
Asked on Apr 22, 2026
Answer
Debouncing is a technique to limit the rate at which a function is executed, ensuring it only runs after a specified delay since the last time it was invoked. This is useful for optimizing performance in scenarios like handling window resize or input events.
<!-- BEGIN COPY / PASTE -->
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
// Usage example
const handleResize = debounce(() => {
console.log("Window resized");
}, 300);
window.addEventListener("resize", handleResize);
<!-- 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").
- It returns a new function that, when invoked, clears the previous timeout and sets a new one.
- The "handleResize" function will only log "Window resized" if the window resizing stops for at least 300 milliseconds.
- This technique helps improve performance by reducing the number of times the function is executed during rapid events.
Recommended Links:
