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 quick succession?
Asked on Feb 03, 2026
Answer
To prevent a function from being executed multiple times in quick succession, you can use a technique called "debouncing". This involves setting a delay before the function is executed, and if the function is called again during this delay, the timer resets.
<!-- BEGIN COPY / PASTE -->
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
const myFunction = () => {
console.log("Function executed!");
};
const debouncedFunction = debounce(myFunction, 300);
// Usage example: attach debouncedFunction to an event
window.addEventListener('resize', debouncedFunction);
<!-- 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").
- The "debouncedFunction" will only execute "myFunction" if 300 milliseconds pass without another call.
- This is useful for optimizing performance in scenarios like window resizing or input events.
- The "apply" method is used to maintain the correct "this" context and pass arguments.
Recommended Links:
