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 runs?
Asked on Mar 08, 2026
Answer
Debouncing is a technique to limit the rate at which a function is executed. It ensures that the function is only called once after a specified delay has passed since the last time it was invoked.
<!-- BEGIN COPY / PASTE -->
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
// Usage example
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 calling the function).
- It returns a new function that can be used in place of the original function.
- The "clearTimeout" method is used to reset the timer each time the debounced function is called, ensuring that "func" is only executed after the specified delay has elapsed without further calls.
- In the example, "handleResize" is debounced to only log "Window resized" if the window resize event stops firing for 300 milliseconds.
Recommended Links:
