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 executes?
Asked on May 28, 2026
Answer
Debouncing is a technique used to limit the rate at which a function is executed. It ensures that a function is only called after a specified delay has elapsed since the last time it was invoked.
<!-- BEGIN COPY / PASTE -->
function debounce(func, wait) {
let timeout;
return function(...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), wait);
};
}
// 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: the function to debounce ("func") and the delay time in milliseconds ("wait").
- It returns a new function that, when invoked, clears the previous timeout and sets a new one.
- The "handleResize" function will only execute if 300ms have passed since the last "resize" event.
- This technique is useful for optimizing performance in scenarios like window resizing or input field changes.
Recommended Links:
