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? Pending Review
Asked on Jun 13, 2026
Answer
Debouncing a function in JavaScript is a technique used to limit how often a function can be executed, ensuring that it only runs after a specified period of inactivity. This is particularly useful for performance optimization in scenarios like window resizing or handling user 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 = 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 parameters: the function to debounce ("func") and the delay in milliseconds ("delay").
- It returns a new function that, when invoked, clears the existing timeout and sets a new one.
- The original function ("func") is only called after the specified "delay" has passed without any new invocations.
- In the example, the "handleResize" function will log "Window resized" to the console only after 300 milliseconds have passed since the last resize event.
- This technique helps prevent excessive function calls during rapid events like window resizing.
Recommended Links:
