DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on

How to create debounce function in raw JavaScript?

A debounce function in JavaScript is a utility function that helps in handling repeated events (such as user input like keystrokes or resize events) by ensuring that a function is not called so often, but only after a certain period of inactivity. This can be useful to improve performance and avoid unnecessary function calls.

Here's a simple example of a debounce function in raw JavaScript:

function debounce(func, delay) {
  let timeoutId;

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

    clearTimeout(timeoutId);

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

// Example usage:
function handleInput() {
  console.log("Input handled");
}

const debouncedHandleInput = debounce(handleInput, 500);

// Attach the debounced function to an event, like an input event
document.getElementById("myInput").addEventListener("input", debouncedHandleInput);
Enter fullscreen mode Exit fullscreen mode

In this example:

  • The debounce function takes two parameters: func (the function to be debounced) and delay (the time to wait before invoking the function after the last call).
  • Inside the returned function, timeoutId is used to keep track of the setTimeout identifier.
  • When the debounced function is called, it clears any existing timeout and sets a new one. If no further calls are made within the specified delay, the actual function (func) is invoked.

You can customize the delay parameter based on your specific requirements. This is a basic example, and there are more advanced debounce implementations, such as leading edge or trailing edge debouncing, depending on whether you want the function to be invoked immediately at the start or end of the delay.

Top comments (0)