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 too frequently?
Asked on Apr 16, 2026
Answer
To prevent a JavaScript 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) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
const handleResize = debounce(() => {
console.log("Window resized");
}, 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 ("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.
- The "handleResize" function will only log "Window resized" if the window resize event stops firing for at least 300 milliseconds.
- This technique is useful for optimizing performance in scenarios like window resizing, scrolling, or input events.
Recommended Links:
