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's called?
Asked on Feb 01, 2026
Answer
Debouncing is a technique to limit how often a function is executed. It ensures that the function is only called after a specified delay has passed without it being invoked again.
<!-- BEGIN COPY / PASTE -->
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
const handleResize = debounce(() => {
console.log("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 ("delay").
- "timeoutId" is used to store the ID of the timeout, which is cleared each time the debounced function is invoked.
- "func.apply(this, args)" ensures that the original function is called with the correct "this" context and arguments.
- In the example, "handleResize" will only log "Resized!" if the window resize event stops firing for at least 300 milliseconds.
Recommended Links:
