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 in response to a frequently fired event?
Asked on Mar 17, 2026
Answer
Debouncing is a technique to limit how often a function is executed, especially useful for events that fire frequently, like window resizing or keypresses. Here's how you can implement a debounce function in JavaScript.
<!-- 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 = () => {
console.log('Window resized');
};
window.addEventListener('resize', debounce(handleResize, 300));
<!-- 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 ("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 helps improve performance by reducing the number of times the function is called.
Recommended Links:
