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 gets called?
Asked on Feb 25, 2026
Answer
Debouncing is a technique to limit how often a function is executed by delaying its execution until after a specified wait time has elapsed since the last time it was invoked. This is useful for optimizing performance in scenarios like handling window resize or scroll events.
<!-- BEGIN COPY / PASTE -->
function debounce(func, wait) {
let timeout;
return function(...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), wait);
};
}
// Example usage:
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 creates a debounced version of a given function "func".
- "wait" is the delay in milliseconds before the function can be called again.
- "clearTimeout" and "setTimeout" are used to reset the delay each time the debounced function is invoked.
- "apply" is used to maintain the correct "this" context and pass arguments to the original function.
- In the example, "handleResize" will log "Window resized" to the console only after the window resize event has stopped firing for 300 milliseconds.
Recommended Links:
