Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I debounce a function to limit its execution frequency?
Asked on Mar 19, 2026
Answer
Debouncing is a technique to limit the frequency of execution of a function, ensuring it only runs after a specified delay since the last invocation. This is particularly useful for optimizing performance in scenarios like window resizing or input events.
<!-- BEGIN COPY / PASTE -->
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
// Example usage:
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 parameters: the function to debounce ("func") and the delay in milliseconds ("delay").
- It returns a new function that, when invoked, clears the previous timeout and sets a new one.
- The "handleResize" function will only execute 300 milliseconds after the last "resize" event.
- This pattern helps in reducing unnecessary function calls and improves performance.
Recommended Links:
