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 in JavaScript?
Asked on Apr 23, 2026
Answer
Debouncing is a technique used to limit the rate at which a function is executed, ensuring it only runs once after a specified delay has passed since the last time it was invoked. This is particularly useful for optimizing performance in scenarios like window resizing or input events.
<!-- BEGIN COPY / PASTE -->
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
// 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 ("delay").
- A "timeoutId" is used to store the timer reference, which is cleared each time the debounced function is called.
- The debounced function will only execute after the specified delay has passed since the last invocation.
- In the example, "handleResize" is debounced to log a message only once every 300 milliseconds during window resizing.
Recommended Links:
