Debounce in JavaScript

What is Debounce? Debounce is used for optimizing the performance of the web app, limiting the rate of execution of a particular function.

In other words, the function is executed after a certain delay, But why do we want to delay the function?

One well-known use case for debounce is the search bar that gives us suggestions while we type, the question here is will you make an API call every time a text in the input changes?

No, right? you don't want to fetch suggestions every time user presses a key, imagine you are searching for "JavaScript videos" 17 characters itself will lead to 17 API calls, Now imagine millions of people using the website typing so many queries every second, this will lead to a lot of API calls and create a huge load on the backend and hinder the performance of the app.

so how do we resolve this we can debounce this function, so only after the user has stopped typing or paused between the words or finished typing then make an API call for fetching the suggestions. Now for the same example if the user types "Javascript" , paused and types "videos" here we are making 2 API calls rather than 17 reducing a lot of API calls.

Let's understand via example

Imagine yourself as a 7-year-old kid who loves chocolates and your mom bought a lot of chocolates from the store today, Now you keep on asking your mom for chocolate so many times that she got annoyed and told you she will give you the chocolate only if you remain silent for one hour, means you won't get anything if you keep on asking her continuously you will only get it one hour later from the last time you have asked for, This is nothing but debouncing.

here are some common use cases:

  • Search bar - wait until the user has finished typing or stopped/paused between typing

  • window resizing - wait until the user finishes resizing then only trigger the function

  • Double-clicking - for people like me who double click on buttons, it prevents double-clicking on buttons

  • Drag and Drop - don't do anything while the drags and drops

  • Scrolling - React scrolling events

Now let's see how we can implement it

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

the debounce function takes a callback function and a delay here we have given 1000ms (1 second) as default, we have a timer initialized, and this function returns another function inside that we are clearing out the timer and creating a new one, the setTimeout delays the callback function with a delay in this case of 1sec if there is a delay of 1 sec then only the function is called.

How to use this?

const displayText= document.querySelector(".debounce");
const ip = document.querySelector("input");

const debounceText = debounce(text => displayText.innerText = text)

ip.addEventListener("input",(e) => {
  debounceText(e.target.value)
})

where displayText is the paragraph reference and ip is the input on which we are adding an event listener input and call the debounceText function

Debounce is great when you want to make a request after everything is changed, like a bunch of changes happening all at once so you can batch them together and send them all of once in the debounce.

I hope you found this useful, Thank you for reading