Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I debounce a function in JavaScript to limit how often it runs?
Asked on Mar 09, 2026
Answer
Debouncing a function in JavaScript involves ensuring that it is only executed after a specified delay period has passed since the last time it was invoked. This is 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 = () => {
console.log("Window resized");
};
window.addEventListener("resize", debounce(handleResize, 300));
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "debounce" function takes two parameters: "func" (the function to debounce) and "delay" (the time in milliseconds to wait before invoking "func").
- "timeoutId" is used to store the ID of the timeout, allowing it to be cleared if the function is called again before the delay period ends.
- The "apply" method ensures that the original function's context and arguments are preserved.
- In the example, "handleResize" is debounced with a 300ms delay, meaning it will only execute if the window resize event stops firing for 300ms.
Recommended Links:
