Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I prevent a function from being executed multiple times in a row quickly in JavaScript?
Asked on May 14, 2026
Answer
To prevent a function from being executed multiple times in quick succession, you can use a technique called "debouncing". Debouncing ensures that a function is only called after a certain amount of time has passed since its last invocation.
<!-- 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("Resize event handled!");
}, 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 and the delay in milliseconds.
- "clearTimeout" is used to reset the timer whenever the debounced function is invoked again within the delay period.
- "setTimeout" is used to call the original function after the specified delay.
- In the example, the "handleResize" function will only be executed 300 milliseconds after the last "resize" event.
Recommended Links:
