Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I prevent a JavaScript function from being called multiple times quickly?
Asked on Jan 19, 2026
Answer
To prevent a JavaScript function from being called multiple times in quick succession, you can use a technique called "debouncing". This involves setting a delay before the function can be called again.
<!-- 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);
// Example usage: This will only log "Function executed!" once, even if called multiple times quickly.
debouncedFunction();
debouncedFunction();
debouncedFunction();
<!-- 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 each time the debounced function is invoked, ensuring the function only executes after the specified delay.
- "apply" is used to maintain the context and pass arguments to the original function.
- In the example, "debouncedFunction" will only execute "myFunction" once if called multiple times within 300 milliseconds.
Recommended Links:
