Thursday, April 9, 2020

debouncing in javascript

So, we have seen the requirements where in which we are required to send the data to the server on an event that might be a click, hover, mouseEnter or anything.

So let us consider we are writing a click event for a button. So the basic code for the same would look something like this:

1
2
3
4
5
$(document).ready(() => {
    $("#btn").on('click', async (event) => {
        // do some api calls or anything
    })
})

Now suppose you are saving/posting the data to the server on every click, in that case if suppose, user clicked the button 2 3 times, it will save the same data 3 times with different ids.

In order to handle this we have 2 options:
  1. either disables the button once you click and enables it once the callback returns
  2. Write a debounce function to handle accidental clicks
Lets see first how debounce function is written.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const debounce = (fn, delay) => {
    let timeoutId;
    return (...args) => {
        if(timeoutId) clearTimeout(timeoutId);
        timeoutId = setTimeout(() => fn(...args),delay)
    }
}

$(document).on('ready', async() => {
    $('#btn').on('click', debounce(e=> {
        console.log('bye bye')
    }, 2000))
})

Explanation:
  1. In this code, we have first created a higher order function named debounce that is taking 2 params, the callback function and a delay to reset the functionality if, someone triggered the event twice.
  2. The debounce function is returning a function that is calling our callback passed at line 5.
  3. Now, instead of giving the callback directly to the event, we are calling debounce and passing our callback function implementation as well as the delay that is going to wait for certain time, before resetting the timeout.
That's it, this debounce function is a nice way of making sure that the accidental triggering of the events can be stopped and only the last event will be considered. This makes sure that all the events that are triggered before the timeout mentioned are going to keep on cancelling unless user stops the event creation and only the last triggered event is accepted and fires the actual callback.

Happy Coding :)

1 comment: