DEV Community

Sahil Thakur
Sahil Thakur

Posted on

Debounce in javascript

This article is originally written here with all the images and code samples -> https://easyontheweb.com/debounce-in-vanilla-javascript/

I still remember when I first got to know about the concept of debounce in web development. I was really amazed about how such a small thing could be so vital for the performance as well user experience for a web application. So, in this article we will look at what debouncing is, why is it important and how can we implement our own debounce function in vanilla Javascript.

We will also see how you can use debounce from libraries like lodash and use them in your React applications just as easily.

What is debounce ? (In UX terms)
Okay, so before think about debounce in terms of functions and code we need to know what debounce is in terms of user experience and where have we seen debounce. One of the first websites that comes to mind when I think of debounce has to be Flipkart . If you visit flipkart, open the network developer tools and start typing on the search bar, you will notice that a request ‘autosuggest’ gets fired. But, on closer observation, you will notice that this request is not actually getting fired on every letter change but after we have given a certain pause during our typing.

What does this mean? This means that the Frontend is not sending a request to the backend for every keystroke but instead is waiting for the user to first type in a certain set of characters and ask for suggestions only when there is break in his typing.

This improves the UX as the user does not keep getting nagging suggestions on every keystroke but actually gets the suggestion only when he has written a certain set of characters that he actually wanted a suggestion for.

What is debounce ? (Technical terms)
Okay, so what is debounce must be clear to you from the user experience point of view but let us also think of it from a more technical POV now. Debounce as I said earlier ensures that a request is sent to the backend only after the user has stopped typing for a certain amount of time. Now, note that this is just one of the use cases for debounce and it is surely not the only use case. Anyways, we’ll only take this use case forward in this article and discuss according to it only.

So, one thing clear from this is that debouncing clearly improves the performance of the web application by reducing the number of requests sent to the backend. This is a very important thing as there could be thousands of users simultaneously typing millions of letters into your application’s search bar let’s say – we do not want the frontend to keep making a request on each keystroke.

What we can think of debouncing as is that we are grouping multiple calls to the backend into a single one.

There are several libraries and plugins that implement debounce in different ways, taking in different optional parameters that fine grain control the debouncing but the main concept more or less remains the same. Let us first try to implement our own debounce function in vanilla Javascript and then take a look at some libraries that you can make use of to use debouncing just out of the box without having to write it yourself.

Writing our own debounce in vanilla Javascript

So, this is just a simple HTML page that we have made that contains nothing but an input field and is loading a javascript file from the same directory called “index.js”.

The only thing worth seeing here is that we are calling a function called debouncedGetData on every key press inside the input field. This function is created in the index.js file that is shown in the next image.

Now, let us carefully see what is happening in this file. We know that the function we are calling in the HTML file was debouncedGetData .

When we look here we see that that function is nothing but another function called getData inside which your real business logic for the function is written (maybe calling an API or something).

The part worth understanding here and why I wrote this article in fact is inside the debounce function. Let us see line by line what is happening inside that function.

As you can see the debounce function takes in two arguments -> another function and a time period which you want to use for debouncing.
The first thing this function does is create a timeout variable.

Next, we return a function from this function (Note that functions are first class citizens in JS and can be passed as arguments or be returned from other functions) which takes in the spread …args which does nothing but passes down the arguments. Then, we store the value of this in a variable called context. This is done to handle a case when we use this debounce function as a method of an object (Will discuss that ahead).

Next, we just clear out any ongoing timeout functions and then use setTimeout with the appropriate wait and use apply on the function that was passed as the argument with the correct context and args.

In terms of debounce concepts you just need to think that that the timeout is set with a 250ms timer on each keypress. Now, if the gap between two keypresses is less than 250ms, the timeout gets cleared and a new timeout with 250 ms is set. Whenever the user gives a break for at least 250ms between consecutive keystrokes, we call our debounced function (getData in this case).

One of the key JS concepts used here is the concept of this, we have written the returned function not as an arrow function on purpose because then it would not have the correct value of this if the function was used as a method of an object. A great article that I read while preparing for this article had this issue greatly discussed here -> https://medium.com/@griffinmichl/implementing-debounce-in-javascript-eab51a12311e

Using libraries for debounce
So, the debounce functionality is available for usage in many different libraries like underscore and lodash but the one I tend to use is the one provided by lodash. Now, there is not much of a difference and if your project already uses the underscore library you can use their debounce functionality.

Now, even though I personally mostly use debounce from libraries in my projects and applications but it is always good to know how debounce works and be able to write your own code for debounce as this is an important concept even when it comes to interview questions and all.

Do you love Javascript ? Want to know the best features being rolled out with EcmaScript 2020 ? Then do check this article out -> https://easyontheweb.com/5-es2020-features-you-should-be-excited-for/

Leave a Reply

Top comments (0)