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 runs during rapid events?
Asked on May 16, 2026
Answer
Debouncing is a technique to limit how often a function is executed during rapid events by delaying its execution until a specified time has passed since the last event. Here's a simple implementation using JavaScript.
<!-- 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 takes two parameters: "func" (the function to debounce) and "wait" (the delay in milliseconds).
- It returns a new function that clears the previous timeout and sets a new one.
- The example demonstrates debouncing a "handleResize" function that logs a message when the window is resized.
- The function will only execute if 300 milliseconds have passed since the last resize event.
Recommended Links:
