Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I prevent a function from being called too frequently in JavaScript?
Asked on Apr 04, 2026
Answer
To prevent a function from being called too frequently, you can use a technique called "debouncing". Debouncing ensures that a function is only called after a specified delay has passed since the last time it was invoked.
<!-- BEGIN COPY / PASTE -->
function debounce(func, delay) {
let timeoutId;
return function(...args) {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
// Example usage:
const logMessage = () => console.log("Function executed!");
const debouncedLogMessage = debounce(logMessage, 2000);
// This will only log "Function executed!" once, 2 seconds after the last call.
debouncedLogMessage();
debouncedLogMessage();
debouncedLogMessage();
<!-- 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").
- Inside the "debounce" function, a "timeoutId" is used to track the timeout.
- The returned function clears any existing timeout and sets a new one, ensuring the original function is only called after the specified delay.
- In the example, "debouncedLogMessage" will only log once, 2 seconds after the last call.
Recommended Links:
