Debounce Function

Shared by: devcanvas

javascript

1
function debounce(func, delay) {
2
    let timeout;
3
    return function (...args) {
4
        clearTimeout(timeout);
5
        timeout = setTimeout(() => func.apply(this, args), delay);
6
    };
7
}
8

9
// Example Usage
10
window.addEventListener('resize', debounce(() => {
11
    console.log('Window resized!');
12
}, 500));
13

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

  1. 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.

  2. Resize Events:
    When the browser window is resized, you might need to update the layout. Debouncing prevents the callback from being executed excessively.

  3. 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

  1. Timeout Management:
    The debounce function maintains a timeout variable. Every time the debounced function is called, it clears the previous timer using clearTimeout.

  2. Delayed Execution:
    A new timer is started using setTimeout. The callback (func) executes only after the delay has passed without further invocations.

  3. apply for Context:
    The func.apply(this, args) ensures that the original function retains its correct context (this) and receives the proper arguments.


Common Pitfalls

  1. 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 the immediate parameter to trigger the callback on the leading edge.

  2. Not Suitable for Constant Execution:
    For use cases requiring continuous function execution at specific intervals, consider the throttle function instead (described below). **

Love it? Share it!

DevCanvas DevCanvas Logo

Online Editor with a collection of awesome frontend code and code snippets for developers of all levels.

Legal & Support

Stand with Palestine 🇵🇸! DO NOT BE SILENCED

© 2025 DevCanvas. All rights reserved.