Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 16, 2021 03:05 pm GMT

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


Original Link: https://dev.to/abhishekjain35/debouncing-in-javascript-276j

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To