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?
Asked on May 11, 2026
Answer
Debouncing is a technique to limit how often a function is executed by postponing its execution until after a specified delay has elapsed since the last time it was invoked. This is useful for performance optimization, especially in scenarios like handling window resizing or input 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 takes two arguments: the function to debounce ("func") and the delay in milliseconds ("wait").
- Inside the returned function, "clearTimeout" is used to reset the timer whenever the function is called again before the delay.
- "setTimeout" is used to call the original function after the specified delay, ensuring it only runs once the delay has passed without further invocations.
- The example demonstrates debouncing a "handleResize" function that logs a message when the window is resized, but only if 300 milliseconds have passed since the last resize event.
Recommended Links:
