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 May 09, 2026
Answer
Debouncing is a technique used to limit how often a function is executed, especially useful in scenarios like handling window resizing or user input events. 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 = 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: "func" (the function to debounce) and "wait" (the delay in milliseconds).
- The "timeout" variable stores the current timeout ID, which is cleared each time the debounced function is invoked.
- The "setTimeout" function delays the execution of "func" by the specified "wait" time.
- The example demonstrates debouncing a "handleResize" function that logs a message when the window is resized, limiting its execution to once every 300 milliseconds.
Recommended Links:
