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 28, 2026
Answer
Debouncing is a technique to limit the rate at which a function is executed, ensuring it only runs after a specified delay has elapsed since the last time it was invoked. This is particularly 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 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 parameters: the function to debounce ("func") and the delay in milliseconds.
- "timeoutId" is used to store the ID of the timeout, allowing it to be cleared if the function is called again before the delay ends.
- "func.apply(this, args)" ensures the original function is called with the correct context and arguments.
- In the example, "handleResize" will only log "Window resized" if the window resizing stops for at least 300 milliseconds.
Recommended Links:
