Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I debounce a function call in JavaScript to limit execution frequency? Pending Review
Asked on Apr 13, 2026
Answer
Debouncing a function in JavaScript ensures that it is only executed after a certain period of inactivity, which is useful for optimizing performance in scenarios like window resizing or input events.
<!-- 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 debouncedLog = debounce(logMessage, 300);
// This will only log "Function executed!" once, 300ms after the last call.
debouncedLog();
debouncedLog();
debouncedLog();
<!-- 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.
- "clearTimeout" is used to reset the timer each time the debounced function is called.
- "setTimeout" schedules the function to be called after the specified delay.
- The "apply" method is used to maintain the correct "this" context and pass along any arguments.
Recommended Links:
