What magic Throttling and Debouncing do to improve web performance .

Debouncing and throttling are the terms used when we talk about web optimization or to control heavy functions attached to an event listener.

DEBOUNCING

In the debouncing technique, no matter how many times the user fires the event, the attached function will be executed only after the specified time once the user stops firing the event. Imagine this happening in a website having a huge codebase, such as Amazon or Flipkart. API calls are expensive, and making an API call on change of every single character will surely affect the performance of your website. Usually In search feature we use debouncing.

function debounce(fn, delay){
let timer;
return function(){
  clearTimeout(timer);
  timer = setTimeout(()=> fn(), delay);
 };
}
  1. we are clearing the timer if it's initialized already

  2. Then we are running setTimeout function, which will run after the delay milliseconds.

  3. So, when a user types again, the previous initialized time will be clear out and new setTimeout timer will run again with new 1-second timing.

  4. If the user writes again, this process will be followed again. Thus we are preventing immediate API calls.

  5. When the user stops typing, then the function will run after 1 second. And then call API.

THROTTLING

Throttling is a technique in which, no matter how many times the user fires the event, the attached function will be executed only once in a given time interval. This usually helps to optimize click event .In infinite scrolling, we can use throttling as we want to load new content after some interval of scrolling, not at every scrolling event.

function throttleFunction(func, delay){
let timerId;

  if(timerId){
    return;
  }

timerId = setTimeout(()=> {
    func(); 
    timerId = undefined;
  },delay)
}
  1. when first scroll event is fired, throttleFunction is called.

  2. firstly, timeId isn't defined. So, if statement will not execute.

  3. setTimeout will run function after 200millisecond. Now timerId is defined.

  4. When 2nd event for the scroll is fired, timerId isn't undefined. timeId isn't undefined means setTimeout function has already been schedules. So, new timerId will not be generated. Therefore, if statement will execute. and will return us out of the function.

  5. This makes sure that before 200 milliseconds, we aren't able to make any API call. This makes sure that API calls will be called only once within the interval.

  6. When the scheduled interval is passed i.e. 200 milliseconds and the user is still scrolling, then our API call will run and schedule another API call for the future i.e. 200 milliseconds later.