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 01, 2026
Answer
Debouncing is a technique used to limit how often a function is executed, especially useful in scenarios like handling window resizing or user input events. Here's how you can implement a debounce function in JavaScript:
<!-- BEGIN COPY / PASTE -->
function debounce(func, wait) {
let timeout;
return function(...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), wait);
};
}
// 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 "wait" (the delay in milliseconds).
- It returns a new function that, when invoked, clears the previous timeout and sets a new one.
- The "handleResize" function will only execute 300 milliseconds after the last "resize" event.
- This technique helps in optimizing performance by reducing the number of times a function is called.
Recommended Links:
