Computer >> Computer tutorials >  >> Programming >> Javascript

What is Debouncing in JavaScript?


Debouncing

Debouncing is nothing but reducing unnecessary time consuming computations so as to increase browser performance. There are some scenarios in which some functionalities take more time to execute a certain operation. For instance, take an example of a search bar in an e-commerce website.

Debrief

For suppose a user wants to get "Tutorix study kit". He types every character of the product in the search bar. After typing each character, there is an Api calling takes place from browser to server so as to get the required product. Since he wants "Tutorix study kit", the user has to make 17 Api calls from browser to server. Think of a scenario that when millions of people making the same search there by calling billions of Api's. So calling billions of Api's at a time will definitely leads to a slower browser performance. To reduce this drawback, Debouncing comes in to picture.

In this scenario, Debouncing will set a time interval, for suppose 2 secs, between two keystrokes. If the time between two keystrokes exceeds 2 secs, then only Api calling will takes place. In those 2 secs the user may type at least some characters, reducing those characters Api calling. Since the Api calling has reduced, the browser performance will be increased. One must heed that the Debouncing function updates for every key stroke.

Example summary

In the following example a button is attached to a event listener that calls a debounce function. Debounce function is provided with 2 parameters, one is a function and the other a number(time). A Timer is declared, which as the name suggests calls debounce function after a specific time.

Once the debounce button clicked, an alert box opens up and displays a message. The function updates every time which means if the button clicked prior to the delay time(2 secs), initial timer will be cleared and fresh timer will be started. To achieve this task clearTimeOut() function is used.

Example

<html>
<body>
<input type = "button" id="debounce" value = "Debounce">
<script>
   var button = document.getElementById("debounce");
   var debounce = (func, delay) => {
      let Timer
      return function() {
         const context = this
         const args = arguments
         clearTimeout(Timer)Timer= setTimeout(() =>
            func.apply(context, args), delay)
      }
   }
   button.addEventListener('click', debounce(function() {
      alert("Hello\nNo matter how many times you" +
      "click the debounce button, I get " +"executed once every 2 seconds!!")}, 2000));
</script>
</body>
</html>

After executing the above function the following button will be displayed

What is Debouncing in JavaScript?

After clicking the button and waiting for 2 secs the following alert box will be displayed as the output.

Output

What is Debouncing in JavaScript?