DEV Community

Cover image for Debouncing in Javascript.
Abhishek Jain
Abhishek Jain

Posted on • Updated on

Debouncing in Javascript.

Debouncing is a pattern that allows delaying execution of some piece of code until a specified time to avoid unnecessary CPU cycles, API calls and improve performance.

Why debouncing?

One word "Performance".

Suppose, you are building an e-commerce application. There you have to implement a search bar for searching products And when the user types in a character, an API call is made.

Look at the example below.

In the above example, we're having a simple searchBar and a count of API calls made. As we type in the searchBar, the count of API called increases with each character. But that's not what we want to happen. What we want is to wait for the user to stop typing. As soon as the user stops typing then we want to make the API call.

so, how can we fix this? - here comes debouncing into play.

Final version with debouncing.

Pretty cool huh?

The debouncing function

Take a look at this debounce function we implemented above.


function debounce(fn, delay) {
  let timer;

  return function () {
    clearTimeout(timer);
    timer = setTimeout(() => fn(), delay);
  };
}

Enter fullscreen mode Exit fullscreen mode

What we are doing here is, initialize a timer then return a function. As soon as the user starts typing the function executes -:

  1. First it clears the timer if it's initialized.

  2. then it assigns the timer setTimeout function, which will run after 1 second if it is not cleared.

  3. if the user types any character within 1 second the function will be called again. But in the above step, we already assigned the setTimeout function to the timer variable. So the clearTimeout will clear the function from the timer variable and also assign a new setTimeout function to the timer variable.

  4. if the user didn't type and 1 second has passed, the function in setTimeout will execute and make the API call.

That's it.

The full version of the debounce function with this and argument binding is -:

function debounce(fn, delay) {
  let timer;

  return function () {
    const context = this;
    const args = arguments;
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(context, args), delay);
  };
}

Enter fullscreen mode Exit fullscreen mode

Well, this is it from my side. See you soon 😁

Top comments (9)

Collapse
 
_genjudev profile image
Larson • Edited

My customers would go crazy if they wait. Debouncing should be limited to a few miliseconds. The user needs the answer right away. Search in google and wait for the results. You would go crazy too. If you realy have problems with your traffic try to cache API results on a server like redis. Have multiply API endpoints in different locations.

Your post is good!

Collapse
 
devdaksh profile image
Daksh Kulshrestha

a simple hack: set a good amount of delay and when users get mad, wait for a day or so and remove the delay and tell them you worked hours to fix the bug.

Collapse
 
abhishekjain35 profile image
Abhishek Jain

Modern problems require modern solutions 😆 😆

Collapse
 
bantya profile image
Rahul Thakare

Best tip ever. 💯

Collapse
 
_genjudev profile image
Larson

And repeat next week.

Collapse
 
abhishekjain35 profile image
Abhishek Jain

Hey Lars, The 1 second delay is just for example. I just wanted the reader to visualise how denouncing works. But in real world the delay is always below 400ms. 🙂🙂

Collapse
 
buriti97 profile image
buridev

very well

Collapse
 
abhishekjain35 profile image
Abhishek Jain

I hope it helped. 😄😄

Collapse
 
andregarvin profile image
andreGarvin

You should not use a delay but rather cancel the action if it is being called again. That js much more efficient that relaying on some delay that will handicap the UX of your application