Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I debounce a function to limit how often it runs?
Asked on Jan 21, 2026
Answer
Debouncing is a technique to limit how often a function is executed by delaying its execution until after a specified wait time has elapsed since the last time it was invoked. This is useful for optimizing performance in scenarios like window resizing or input events.
<!-- BEGIN COPY / PASTE -->
function debounce(func, wait) {
let timeout;
return function(...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), wait);
};
}
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 time in milliseconds ("wait").
- It returns a new function that, when invoked, clears any existing timeout and sets a new one.
- The "handleResize" function is a debounced version of a function that logs "Window resized" to the console.
- The "resize" event listener on the window uses the debounced "handleResize" function to limit how often the resize logic runs.
Recommended Links:
