Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I debounce a function call in JavaScript to limit its execution rate?
Asked on Mar 24, 2026
Answer
To debounce a function in JavaScript, you can use a technique that delays the execution of the function until after a specified wait time has elapsed since the last time it was invoked. This is useful for limiting the rate at which a function is called, such as handling window resize or input events.
<!-- BEGIN COPY / PASTE -->
function debounce(func, wait) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, 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: the function to debounce ("func") and the wait time in milliseconds ("wait").
- It returns a new function that, when invoked, clears the existing timeout and sets a new one.
- The example shows 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.
- This technique helps improve performance by reducing the number of times the function is executed during rapid events.
Recommended Links:
