Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I debounce a function to limit its execution frequency in JavaScript?
Asked on Mar 13, 2026
Answer
Debouncing is a technique used to limit the rate at which a function is executed, ensuring it only runs after a specified period of inactivity. This is particularly useful for optimizing performance in scenarios like handling window resize or scroll events.
<!-- BEGIN COPY / PASTE -->
function debounce(func, wait) {
let timeout;
return function(...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), wait);
};
}
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 in milliseconds ("wait").
- A "timeout" variable is used to store the current timeout ID.
- The returned function clears the existing timeout and sets a new one, ensuring the original function only executes after the specified delay.
- In the example, "handleResize" is debounced to log a message only if 300ms have passed without additional resize events.
- This technique helps improve performance by reducing the frequency of function calls during rapid events.
Recommended Links:
