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 in JavaScript?
Asked on Apr 24, 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 logMessage = () => console.log("Function executed!");
const debouncedLogMessage = debounce(logMessage, 300);
// Call the debounced function multiple times
debouncedLogMessage();
debouncedLogMessage();
debouncedLogMessage();
// "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 ("func") and the delay in milliseconds.
- It returns a new function that, when invoked, clears the previous timeout and sets a new one.
- The "apply" method is used to call the function with the correct "this" context and arguments.
- This technique is useful for optimizing performance in scenarios like window resizing or input events.
Recommended Links:
