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 Feb 13, 2026
Answer
Debouncing is a technique to limit the rate at which a function is executed, ensuring it runs only after a specified delay has passed since the last time it was invoked. This is useful for optimizing performance in scenarios like handling window resize or scroll 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 handleResize = debounce(() => {
console.log('Window resized');
}, 300);
window.addEventListener('resize', handleResize);
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "debounce" function takes two arguments: "func" (the function to debounce) and "delay" (the time in milliseconds to wait before executing the function).
- A "timeoutId" variable is used to store the reference to the timeout, allowing it to be cleared if the function is called again before the delay.
- The "apply" method is used to ensure the original function's context and arguments are preserved.
- In the example, "handleResize" is a debounced version of a function that logs "Window resized" to the console, triggered by the window's resize event.
Recommended Links:
