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 Jan 28, 2026
Answer
Debouncing is a technique used to limit the rate at which a function is executed by delaying its execution until after a specified wait time has elapsed since the last time it was invoked.
<!-- BEGIN COPY / PASTE -->
function debounce(func, wait) {
let timeout;
return function(...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), wait);
};
}
// 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 ("wait").
- 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 technique is useful for performance optimization, especially with events like "resize" or "scroll".
Recommended Links:
