DEV Community

hebasaadosman
hebasaadosman

Posted on

Debounce in JavaScript

Debouncing is a technique used in JavaScript to control the frequency of executing a function that is triggered by an event, such as a button click or key press. It ensures that the function is called only once after a specific period of inactivity, regardless of how many times the event is actually fired during that period.

Here's a simple implementation of debouncing in JavaScript:

function debounce(func, delay) {
  let timerId;

  return function() {
    const context = this;
    const args = arguments;

    clearTimeout(timerId);
    timerId = setTimeout(function() {
      func.apply(context, args);
    }, delay);
  };
}

// Example usage
function handleButtonClick() {
  console.log("Button clicked!");
}

const debouncedButtonClick = debounce(handleButtonClick, 300);

// Attach debounced function to button click event
document.getElementById("myButton").addEventListener("click", debouncedButtonClick);

Enter fullscreen mode Exit fullscreen mode

In the code above, the debounce function takes two parameters: func (the function to be debounced) and delay (the amount of time to wait before invoking the debounced function).

Within the returned function, a timer is used to clear any previously set timeouts. After clearing the timeout, a new one is created using setTimeout with the specified delay. This ensures that the debounced function will be called only after the specified delay has elapsed without any new invocations.

In the example usage, the handleButtonClick function is wrapped with debounce, creating a new function debouncedButtonClick. This debounced function can then be attached to the button click event, ensuring that handleButtonClick will be called only once after a 300ms inactivity period.

Top comments (0)