Debounce and Throttle

During development, we might need to control event triggers in various ways. Concepts like throttle and debounce can be used for achieving the same.

Debounce -

Let say, while resizing the window, UI should be responsive. When you resize the screen, callback method will be called to re-render components according to the screen size.

Now I see two things happening in this case:

  1. Pool of unnecessary calls to the callback is made when user is still resizing.
  2. Too many calls made to the callback method on resize event which will re-render all the components in the page. In other words, if frequent call are made to the callback then the performance of the site might also get impacted.

In this case, we can debounce callbacks.

Debounce is to call a method only after the event trigger stops for x seconds of time delay.
const debounce = (callback, delay) => {
let timeoutHandler = null;
return function(e) {
if(timeoutHandler) {
clearTimeout(timeoutHandler);
}
timeoutHandler = setTimeout(() => {
callback(e);
}, delay);
};
}

Applying debounce in above scenario will let you call resize call-back only when the resize is done.

Other applications of debounce can be:

To use debounce with auto-search, instead of making search call as and when the user types, debounce can be used to make search call when the user stops typing for x time delay.

Similarly, for auto-save feature (present in most of the editor now a days), debounce is used.

Throttle -

Let say, when you scroll through the page, callback method is called to fetch data and render on the page. On every scroll event the method is call and it adds data to page. Now I see two things happening here :

  1. More data is getting added than it is visible to the user on each scroll.
  2. Too many calls made to the callback method on scroll event which will again take time to process data.In other words, if frequent call are made to the callback then the performance of the site might also get impacted.

In this case, callback can be modified to get called once per second. This is where throttle comes into picture. Throttling the callback method will let it call the n times in m seconds.

Throttle is to limit the number of callbacks to a event in a given time.
const throttle = (callback, delay) => {
let lastCall = 0;
return function(e){
const startTime = new Date().getTime();
if(startTime - lastCall < delay ){
return;
}
lastCall = startTime;
callback(e);
};
};

Applying throttle to the above scenario will let the scroll callback method to not overflow with calls.

Debounce and throttle might sound similar but there is very subtle difference between there use case.

Implementation of debounce and throttle.