Debounce in JS - How and When to use?
Tags: javascript, frontend, webdev, productivity
Published: 2022-02-02 14:45:06

Photo by <a href="https://unsplash.com/@ellenqin?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Ellen Qin</a> on <a href="https://unsplash.com/@ellenqin?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
  

As we go through our developer journey...when working on a bug or trying to improve performance of our app we will definitely come across the words debouncing and throttling.

Now we are going to discuss only about debouncing.
##So...What is Debouncing ?

> Debouncing is a method which prevents a function from executing if it gets called or invoked too frequently.

Let's say we have a **Button** and on clicking it we call a function which prints _Clicked_ to the console. What if we clicked twice or thrice at once? The message _Clicked_ will be logged as many times as we clicked the button.

But this is not ideal in many cases. Say we have a button for submitting a form for creating a new user. If the button gets clicked multiple times, multiple users might be created in the database with same details. This must be prevented.

In situations like these we can use **debouncing**.

##Coding our debounce method

Now let's create a live demo of the debounce method. Open up the inspect tab and switch to the console.

```javascript
let likeBtn = document.getElementById('reaction-butt-unicorn')
```

Paste the above code in the console and click enter. This selects the unicorn icon that you see on the left side of this post and assigns it to the variable **likeBtn**.

Next we'll create a function called **printToConsole** and add an _onclick_ event listener to the **likeBtn**.

```javascript
function printToConsole() {
  console.log('Unicorn was clicked')
}
```

```javascript
likeBtn.onclick = printToConsole
```

Now click the unicorn icon and see that the message gets logged to the console and the count increases as many times as you click it. Try clicking it twice or thrice instantaneously. Still the message gets logged as many times as you click it.

Let's write a debounce method which will change the way our button behaves.

```javascript
function debounce(fn, waitTime) {
  let timer;
  return function() {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => fn(), waitTime);
  }
}
```

```javascript
likeBtn.onclick = debounce(printToConsole, 300)
```

Now let's see how the button behaves. Try clicking the icon multiple times at once. What do you see?..... 

The message is logged only once after a delay of 300ms even though the icon was clicked multiple times. 

Even though the button was clicked multiple times at once, we see that it gets logged only once after we stop clicking it.

The reason for this is that a new timer is created every time we click the button and our function will run when the timer reaches the _waitTime_. If the button gets clicked when a timer is running, the previous timer will be destroyed and a new timer will be created.

You should've gotten the idea of why and how to use debouncing.

But the function we wrote doesn't take any arguments. If we want to pass arguments to our function, the method should be written in this way.

```javascript
function debounce(fn, waitTime) {
  let timer;
  return function(...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => fn(...args), waitTime);
  }
}
```

This is only one version of debounce implementation. If you want to look at other implementations you can checkout some well known libraries which have their own implementation.

Like....

[lodash](https://lodash.com/docs/4.17.15#debounce), [jQuery](https://benalman.com/projects/jquery-throttle-debounce-plugin/)

That's all for debounce in the next post we'll talk about throttling.

Please leave a comment if you find anything that can be improved or corrected.

Thank you!!!!