DEV Community

Cover image for The Effect of Debouncing in JavaScript Event handlers
jayakrishnan TN
jayakrishnan TN

Posted on

The Effect of Debouncing in JavaScript Event handlers

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?

If you read my previous article about Event Throttling, 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:


<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:


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

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 🏄‍♂ī¸â›šī¸â€â™‚ī¸đŸš´â€â™€ī¸đŸ¤ŠđŸ¤—!!!.

Top comments (1)

Collapse
 
jkjaikrishna profile image
jayakrishnan TN

We call also do debouncing using helper packages like lodash( _ )