The Effect of Debouncing in JavaScript Event handlers
Tags: javascript, webdev, coding, todayilearned
Published: 2020-07-08 13:49:56

---
title: The Effect of Debouncing in JavaScript Event handlers
published: true
description: The easiest way of learning about event debouncing and how it differs from the throttling concept in Javascript.
tags: javascript, webdev, coding, todayilearned
cover_image: https://redd.one/static/2547a7f25a35127d6b8bb019466514e4/5d2fb/thumbnail.jpg
---

Did every keypress in the search bar need an API call? how a scroll or resize event can be optimized? Such questions are common in platforms like StackOverflow, GitHub, etc.

Did you guys read the same paragraph that I wrote above this line anywhere? 


{% link https://dev.to/jkjaikrishna/all-javascript-apps-need-event-throttling-p88 %}


If you read my previous article about [Event Throttling](https://dev.to/jkjaikrishna/all-javascript-apps-need-event-throttling-p88), you can see that the article also starts with the same paragraph. Why I provide the same paragraph for both? That's also a question..Yeah!! Because these two articles/ concepts that point to the single source of the event optimization.


>*__Debouncing__ and __Throttling__ techniques are used to limit the number of times a function can execute*.

From my last article, the concept of providing a __throttling__ function in an event handler is really simple..ah?

In throttling technique, __timerId__ is the key and in Debouncing `ClearTimeout` function is the key factor.


The concept is really simple:
> _If an event trigger occurs repeatedly in a time period and we need the result only after a cooling period after the event triggers, then we need **Debouncing**_. 

For example, a typo master is trying to search for something in amazon using the top search bar in the web application. He doesn't look into the autocomplete option provided by amazon ( UX is always the king..!🔥🔥🔥) and he waits for the result only after stop typing. So from a developer perspective, we need to call the AutoComplete suggestion API only after he/she stops typing.

There is only one question left to solve the issue. How we Identify the user stopped typing and wait for API response? 

##Solution


Set a cooling period for your event handler. For each event trigger, start the cooling period and if there were any more event triggers occur, then clear the first cooling period and start a new one. If the cooling period is successfully passed then only trigger the API call.

Does that mean we are always clear out the event that occurs repeatedly in the cooling time span.right? Let's come to the coding phase...


The sample `index.html` file is:

```html

<div id= "search-section">
    <input type= "text" placeholder= "Search here" id= "search-input" />
</div>
    
<p>No of times event fired without debouncing</p>
<p id='show-without-debounce-count'></p>

<p>No of times debouncing executed the method</p>
<p id="debounc-count"></p>

<script src= "script.js" />

```

the javascript `script.js` file is:

```javascript

const searchSection = document.getElementById('search-section');
const searchInput = document.getElementById('search-input');
let timerId;

// This represents a very heavy method. Which takes a lot of time to execute
function makeAPICall() {
    let debounceCountDOM = document.getElementById('debounc-count');

    let debounceCount = debounceCountDOM.innerHTML || 0;
    debounceCountDOM.innerHTML = parseInt(debounceCount) + 1;
    console.log('debounce count', debounceCount);

}

function debounceFunction(func, delay) {
    
    //Cancel the current setTimeOut execution 
    clearTimeout(timerId);

    //Execute the function func after delay time
    timerId = setTimeout(func, delay);
}

// Event listener on the search input tag
searchInput.addEventListener('keypress', function() {
    let normalCountDOM = document.getElementById('show-without-debounce-count');
    let normalCount = normalCountDOM.innerHTML || 0;

    normalCount = parseInt(normalCount) + 1;
    normalCountDOM.innerHTML = normalCount;

    console.log('normal count', normalCount);

    debounceFunction(makeAPICall, 200);
});

```

##Result

![event-debouncing](https://www.dropbox.com/s/gtddoui20vco6f5/js-debouncing.gif?raw=1)



##Explanation

I think the code says all the things...Yeah? Let me give a shot also.

Here the __debounceFunction__ will call the __makeAPICall__ function only after provided delay of 200 milliseconds.

Inside __debounceFunction__, each time a new event occurs before completing the previous one, it will clear the _timeId_ with `clearTimeout` function and set a new one with `setTimeout` function. so only when no events are repeated in the delay time span, the `setTimeout` will finish it's execution properly. then only the __makeAPICall__ function will execute.


##Conclusion
Nothing more..nothing less...Debouncing is cool...
We can optimize the no of event triggers with a cooling period for search events, resize events, Mouse moves events, etc.

Further Discussion on this topic in the comment box is appreciated 🏄‍♂️⛹️‍♂️🚴‍♀️🤩🤗!!!.