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 Feb 12, 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 executed 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) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
const logMessage = () => console.log("Function executed!");
const debouncedLogMessage = debounce(logMessage, 300);
// Example usage: Call debouncedLogMessage multiple times
debouncedLogMessage();
debouncedLogMessage();
debouncedLogMessage();
// "Function executed!" will only be logged once, 300ms after the last call
<!-- 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").
- "timeoutId" is used to store the ID of the timeout, allowing it to be cleared if the function is called again before the delay.
- "func.apply(this, args)" ensures the original function is called with the correct context and arguments.
- In the example, "debouncedLogMessage" is called multiple times, but "logMessage" will only execute once, 300 milliseconds after the last invocation.
Recommended Links:
