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's called during repeated events?
Asked on Jan 27, 2026
Answer
Debouncing is a technique used to ensure that a function is only executed once after a specified delay period, even if it's triggered multiple times in quick succession. This is useful for optimizing performance during events like window resizing or keypresses.
<!-- 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 = () => {
console.log("Resized!");
};
window.addEventListener("resize", debounce(handleResize, 300));
<!-- 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, when invoked, clears the previous timeout and sets a new one.
- The "apply" method is used to maintain the correct "this" context and pass any arguments to the original function.
- In the example, the "handleResize" function will only log "Resized!" once every 300 milliseconds during window resizing.
Recommended Links:
