Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I debounce a function in JavaScript to limit its execution rate? Pending Review
Asked on Apr 30, 2026
Answer
Debouncing is a technique to limit the rate at which a function is executed. It ensures that the function is only called after a certain amount of time has passed 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);
};
}
// Usage example
const debouncedFunction = debounce(() => {
console.log("Function executed!");
}, 300);
// This will call the debounced function, but it will only execute once every 300ms
window.addEventListener('resize', debouncedFunction);
<!-- 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 called, clears the previous timeout and sets a new one.
- The debounced function will only execute after the specified "wait" time has passed since the last call.
- In the example, the "debouncedFunction" is used to limit the execution of a function during window resize events.
Recommended Links:
