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 rate in JavaScript?
Asked on Mar 06, 2026
Answer
Debouncing is a technique to limit the rate at which a function is executed, ensuring it only runs after a specified delay since the last invocation. This is useful for optimizing performance in scenarios like handling window resize 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 arguments: the function to debounce ("func") and the delay in milliseconds ("delay").
- It returns a new function that, when invoked, clears any existing timeout and sets a new one.
- The "handleResize" function will only execute 300 milliseconds after the last "resize" event.
- This approach helps in reducing the number of times a function is called, improving performance in scenarios with frequent events.
Recommended Links:
