Hemendra Khatik
aamchora

aamchora

What is debouncing in JavaScript?

Hemendra Khatik's photo
Hemendra Khatik
·Jun 28, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

While building an app using JavaScript. We may need to call the function many times to achieve the desired result.

Some examples are

  • While scrolling or resizing the screen you would want to compute something.
  • Sometimes we may need to display quick results as user types in the input field.

google search

Let's see, how we usually write code to achieve the desired result.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Debouncing</title>
    </head>
    <body>
        <input class="search" type="text" placeholder="search"/>
        <script src="index.js"></script>
    </body>
</html>

let count = 0;
function search(query){
   // some api call
   console.log("result",count++)
}

document.querySelector(".search").addEventListener("input",(e)=>{
search(e.target.value);
})

example one

In the above example, If I search for a laptop, The function search will be called 6 times. Which is an inefficient way of calling a function. And it is very expensive for JavaScript.

You must be wondering what do you mean by expensive for JavaScript?

wondering man

JavaScript is a synchronous single-threaded language. Which means we have a single callstack to execute everything. And because it is single-threaded, we should not block the thread by calling functions unnecessary.

understanding boy

But wait ...

How do we prevent unnecessary function calls to improve performance?

questioning man

Here, the concept of debouncing kicks into the picture.

Kicks in

Debouncing is a technique used to improve the browser's performance. It ensures that time-consuming tasks do not fire so often, In other words, it limits the rate at which a function gets invoked.

Let's re-write the above code using Debouncing technique.


let count = 0;
function search(query){
   // some api call
   console.log("result",count++)

}

const magicFunction = debounce(search,300);

function debounce(func, delay){
  let timer;
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func(...args);
    }, delay);
  };
}

document.querySelector(".search").addEventListener("input",(e)=>{
  magicFunction(e.target.value);
});

example two

The idea behind debouncing technique is that we do not call function during the event but after the event.

In the above example, We can clearly see.

debounce is a higher order function(HOF). Which takes two parameters the first parameter will be a function and the second will be a delay.

If the delay between two keystrokes is less than 300ms, function will not execute and setTimeout will be destroyed. And if the delay is more than 300ms, then only function will execute.

That's how we can implement the debouncing technique to improve our app's performance


follow me for more such blog posts.

Let me know if this blog was helpful.

Twitter || Linkedin

Did you find this article valuable?

Support Hemendra Khatik by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors