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? Pending Review
Asked on Mar 27, 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 specified delay has passed since the last time it was invoked.
<!-- BEGIN COPY / PASTE -->
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
// Example usage:
const debouncedFunction = debounce(() => console.log("Function executed!"), 300);
// Call the debounced function multiple times
debouncedFunction();
debouncedFunction();
debouncedFunction();
// "Function executed!" will be logged only once, 300ms after the last call
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "debounce" function takes two arguments: the function to debounce and the delay in milliseconds.
- It returns a new function that, when invoked, clears the previous timeout and sets a new one.
- The function will only execute after the specified delay has passed since the last call.
- This is useful for optimizing performance in scenarios like window resizing or button clicks.
Recommended Links:
