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? Pending Review
Asked on Feb 22, 2026
Answer
Debouncing is a technique used to limit the rate at which a function is executed. It ensures that the function is only called after a specified delay has elapsed 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);
};
}
// Usage example:
const logMessage = () => console.log("Function executed!");
const debouncedLogMessage = debounce(logMessage, 1000);
// Call the debounced function
debouncedLogMessage();
debouncedLogMessage();
debouncedLogMessage();
// "Function executed!" will be logged only once after 1 second
<!-- 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 ("delay").
- It returns a new function that clears the previous timeout and sets a new one each time it's called.
- The "apply" method is used to maintain the correct "this" context and pass arguments to the original function.
- In the example, "debouncedLogMessage" will only log "Function executed!" once, no matter how many times it's called within the 1-second delay.
Recommended Links:
