Debouncing and Throttling(part 1)

Why we want to use Debounce or Throttling Techniques:

1.To improve performance of a website 2.The way this is done by reducing number of times a particular action is taken

Without Debounce or Throttling:

lets take an example, we have to auto complete the search bar in website i mean if i type john in then seachbar should recommend john doe

without debounce for every key press we will hit the network request and we wait for response and will render suggestions on UI

So if we type john we will make 4 api calls from single user with in short period of time, so what if thousands of users are using your website and searching, eventually we will end up with thousands multiple requests so this costs website to handle all requests and users time and their data so somehow we have to reduce the network calls to get desired output that is where these techniques comes into the picture.

Debounce:

debounce is one such technique where will make network call if there is a certian delay between different key presses from the users

for example if i'm typing john continously then we won't make any network call if i stops after typing john then we will make the network call.

export default function App() {
  // debounce function
  const debounceFn = (cb, delay) => {
    let timerId;
    return (...text) => {
      clearTimeout(timerId);
      timerId = setTimeout(() => cb(text), delay);
    };
  };

  let apiFn = debounceFn((text) => console.log(text), 1000);

  return (
    <div className="App">
      <input type="text" onChange={(e) => apiFn(e.target.value)} />
    </div>
  );
}
  1. In the above code we have debouncefn which is taking two parameters one is callback and other is delay

2.debounce function returning ananomous function,this is the function is a wrapper for callback

  1. wrapper function will help us to clear the callback function or will help us to call the callback function

4.if we type first key it will calls the api fn(which is a wrapper fn) so it uses the SetTimout fn which schedules the network call after given delay

  1. if user types agian even before completing previous scheduled network call then api function will clear the previous scheduled request and it will shcedule the new request

  2. it will keep on going until and unless there is a given delay time gap between two key presses.

That's all about debounce technique will cover throttling technique in part 2

reference:

geeksforgeeks.org/debouncing-in-javascript/...