Debounce Function in JavaScript

Debounce function limits the rate at which a function can fire. For example, a user authentication form where user can provide their credentials and click on the button to log in. Users can click multiple times on the same button which would in turn calls the function multiple times. This will unnecessarily load the browser with so many function calls.

To tackle this scenario, a debounce function is used. In this tutorial, we will learn how to create a Debounce function in JavaScript.

Consider this HTML code.

<button id="sayHello" onclick="sayHello()">Click me</button>

When the user click on the button, a function sayHello() will be called.

sayHello() => {
  console.log("You have clicked a button");
}

In a normal scenario, if you click on this button 50 times in a minute, the browser will execute the sayHello() function 50 times.

To tackle this, we create a debounce function. Debounce function accepts two arguments, the first argument is the function to execute and the second argument is the time delay. Here is the code.

const debounce = (fn, delay) => {
  let timeOutId;
  return function(...args) {
    if(timeOutId) {
      clearTimeout(timeOutId);
    }
    timeOutId = setTimeout(() => {
      fn(...args);
    },delay);
  }
}

Our function accepts two arguments, first a function to execute, and the second argument is the delay in milliseconds.

In the first run, when the debounce function is called, we call the setTimeout() function to create a delay and once the timeout is complete, we execute the function.

If the debounce function is called between the delay, we simply reset the timer and create a new delay using setTimeout() function.

Let’s use our debounce function.

const printMessage = () => {
  console.log("You have clicked a button");
};

const sayHello = debounce(printMessage,2000);

Now when a user clicks on the button, a debounce function will be called with a delay of 2 seconds. If a user clicks on the button again within the 2 seconds delay, the debounce function will reset the timer.

So now, if you click 50 times in 1 second, the browser will execute the function once after the delay is over.

This is the Debouncing function in JavaScript for you. You can check the live demo of the code in the codepen.

See the Pen
Debounce function in JavaScript
by Shahid Shaikh (@codeforgeek)
on CodePen.

Pankaj Kumar
Pankaj Kumar
Articles: 207