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 Mar 11, 2026
Answer
Debouncing is a technique to limit the rate at which a function is executed, ensuring it only runs after a specified delay following the last call. This 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);
};
}
// Example usage:
const logMessage = () => console.log("Function executed!");
const debouncedLogMessage = debounce(logMessage, 300);
// Attach to an event
window.addEventListener('resize', debouncedLogMessage);
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "debounce" function takes two parameters: "func" (the function to debounce) and "delay" (the time in milliseconds to wait before executing the function).
- "timeoutId" is used to store the reference to the timeout, allowing it to be cleared if the function is called again before the delay expires.
- The "debouncedLogMessage" is an example of how to use the debounced function, which logs a message to the console only after 300 milliseconds have passed since the last resize event.
Recommended Links:
