Debounce Function
Shared by: devcanvas
javascript
|
|
|
|
|
|
|
|
|
|
|
|
|
A debounce function ensures that a given function is executed only after a specified delay has elapsed since the last time it was invoked. This is particularly useful for performance optimization in scenarios where an event is triggered repeatedly, like scroll
, resize
, or keypress
.
The debounce
function works by delaying the execution of the callback function (func
) until no further events occur within the specified time (delay
in milliseconds). If the event keeps occurring, the timer resets, ensuring that the callback is executed only once after the event “calms down.”
Real-World Use Cases
-
Search Input Suggestions:
When a user types in a search box, you don’t want to send a request to the server after every keystroke. Debouncing ensures the request is sent only after the user stops typing. -
Resize Events:
When the browser window is resized, you might need to update the layout. Debouncing prevents the callback from being executed excessively. -
Button Click Handling:
If a button triggers expensive operations (e.g., API calls), debouncing ensures that accidental double-clicks don’t lead to duplicate requests.
How It Works
-
Timeout Management:
Thedebounce
function maintains atimeout
variable. Every time the debounced function is called, it clears the previous timer usingclearTimeout
. -
Delayed Execution:
A new timer is started usingsetTimeout
. The callback (func
) executes only after the delay has passed without further invocations. -
apply
for Context:
Thefunc.apply(this, args)
ensures that the original function retains its correct context (this
) and receives the proper arguments.
Common Pitfalls
-
Instant Execution:
If you need the function to execute immediately on the first event (and then debounce), you’ll need to modify the implementation:function debounce(func, delay, immediate = false) { let timeout; return function (...args) { const callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(() => { timeout = null; if (!immediate) func.apply(this, args); }, delay); if (callNow) func.apply(this, args); }; }
Pass
true
for theimmediate
parameter to trigger the callback on the leading edge. -
Not Suitable for Constant Execution:
For use cases requiring continuous function execution at specific intervals, consider the throttle function instead (described below). **