How to debounce a function in JavaScript
Debouncing prevents excessive function calls by delaying execution until after a specified period of inactivity. As the creator of CoreUI with over 25 years of JavaScript development experience, I’ve implemented debouncing extensively in search inputs, resize handlers, and user interaction events. From my expertise, the most effective approach is creating a closure that manages a timer, clearing previous timeouts when new calls occur. This technique dramatically improves performance by ensuring functions execute only after user activity stops.
Create a debounce function that delays execution until after a specified period of inactivity.
function debounce(func, delay) {
let timeoutId
return function(...args) {
clearTimeout(timeoutId)
timeoutId = setTimeout(() => func.apply(this, args), delay)
}
}
Here the debounce function returns a new function that manages a timeoutId variable through closure. When called, it clears any existing timeout with clearTimeout(timeoutId) and sets a new one with setTimeout(). The function only executes after the specified delay period passes without additional calls. The func.apply(this, args) ensures the original function receives the correct context and arguments.
Best Practice Note:
This is the same approach we use in CoreUI components for search inputs and scroll event optimization. Debouncing is ideal for events that fire rapidly like keystrokes, window resizing, or API calls triggered by user input.



