DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on • Edited 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.

Support My Work ❤️

If you enjoy my content and find it valuable, consider supporting me by buying me a coffee. Your support helps me continue creating and sharing useful resources. Thank you!

Connect with Me 🌍

Let’s stay connected! You can follow me or reach out on these platforms:

🔹 YouTube – Tutorials, insights & tech content

🔹 LinkedIn – Professional updates & networking

🔹 GitHub – My open-source projects & contributions

🔹 Instagram – Behind-the-scenes & personal updates

🔹 X (formerly Twitter) – Quick thoughts & tech discussions

I’d love to hear from you—whether it’s feedback, collaboration ideas, or just a friendly hello!

Disclaimer

This content has been generated with the assistance of AI. While I strive for accuracy and quality, please verify critical information independently.

Top comments (0)