Debounce and why we use it?

Debounce and why we use it?

Have been working with JavaScript for quite a long time, and every day there is new learning one of the things that I learned recently is debouncing and throttling. So in this blog, I will tell you about debouncing, why debouncing, and how to implement it.

So there are chances we might be using some functionality in our app, for which we have to call a particular event multiple times, like implementing an event on a scroll or doing a search that fires an event every time we type a word.

Let's take the example of search here. How does our search work? Most of the time we build our search functionality when the user starts typing it starts firing the search event on every keystroke. For a small data to be searched on its not an issue, we will get our results. But if data is quite large like we are searching in a database which has around more than lakhs of data. Then it will take some time. Not necessary we will be having this data at our disposal. Sometimes we might be calling some API's to get the results. Calling an API's is quite an expensive task, If we fire API on every keystroke, then our app will become slow and who likes to use a slow app. To solve this there exist debouncing using this we can limit our APIs to be fired according to our need and not on every keystroke.

So lets take a search bar example without debouncing.

import React from 'react';

export default function App() {
  const getSearchResult= (e) => {
    console.log(e.target.value);
  };

  return (
    <div>
      <input type="text" onChange={getSearchResult} />
    </div>
  );
}

Here I have a input search bar in which user can search data. But currently it will just log the query. Don't get into the functionality just try to understand the logic in this. Whenever I press a keystroke it fires an console event with the data present in search field. Take the log statement as an external API so you can see it is calling an API for every keystroke.

So you will see your search working like this. It will console on every keystroke with the data present in search field.

Screenshot 2022-06-09 at 1.13.23 AM.png

So its not a bad thing to use search functionality like this, but if you want your app to be faster and you are more concerned about the performance of the app then you can implement the debounce functionality for your app.

Before getting started with implementation of debouncing. Lets understand how debounce will help us in this case. So instead of firing search event one every keystroke, what we will do we will set a timer so that the event should be fired after some time and by the that time user should have typed some characters. Whenever after typing if a user takes a break for example 500ms it will trigger the search event after that time. It will not trigger any event when user is typing.

Lets implement the debounce function first.

const debounceSearch = (callbackFunc, T) => {
  let timer;
  return function () {
    const context = this,
    const args = arguments;
    clearTimeout(timer);
    timer = setTimeout(() => {
      callbackFunc.apply(context, args);
    }, T);
  };
};

So this debounceSearch function will take your original getSearchResult function and T(time delay). it create a timer variable and return a callback function now you can execute that returned function. Now it work like normal search function but it is more optimized version. It first clears the timeout and create a new setTimeout for every keystroke and will only call the original search function after a given time is passed.

export default function App() {
  const handleChange = (e) => {
    console.log(e.target.value);
  };

  const search = debounceSearch(handleChange,300);
  return (
    <div>
      <input type="text" onChange={search} />
    </div>
  );
}

Now If you do the search it will work more efficiently. So If I keep typing it will not fire the search event it will only fire the search event, when I am idle for minimum 300ms and output in console will look like this.

Screenshot 2022-06-09 at 1.13.44 AM.png

Thanks for reading :)