Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I prevent a JavaScript function from executing multiple times in quick succession?
Asked on May 12, 2026
Answer
To prevent a JavaScript function from executing multiple times in quick succession, you can use a technique called "debouncing". Debouncing ensures that a function is only called once after a specified delay period has passed since the last time it was invoked.
<!-- BEGIN COPY / PASTE -->
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
// Usage example
const handleResize = debounce(() => {
console.log("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 track the current timeout. "clearTimeout" is called to reset the timer whenever the debounced function is invoked.
- The "setTimeout" function is used to call the original function after the specified delay.
- In the usage example, the "handleResize" function will only log "Resized!" once every 300 milliseconds, regardless of how many times the "resize" event is triggered within that period.
Recommended Links:
