Introduction

In this article, we will discuss Debouncing and throttling techniques that can be use to optimize the performance of web app by preventing unnecessary API calls and load on the server. Both this techniques may look similar but they are not, use case scenarios of both them are very different.

Debouncing

What is a debounce?

Deboucing is technique to delay execution of invoked function for specific time duration and if the same function gets invoked again in that time duration then again delay the execution of this newly invoked function for specific time duration by scrapping the previous function call.

In other words, execution of function is delayed until it aggregates the input to function in specified time interval to save the frequent and unnecessary server calls. This can be achieved by passing the actual function to Debouncing function and hence we call it as the function is being debounced.

Lets see the generic debouce function in plain vanilla JavaScript.


const debounce = (invokedFunction, waitingTime) => {
  let timeoutId;

  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeoutId);
      invokedFunction(...args);
    };

    if(timeoutId){
      clearTimeout(timeoutId);
    }
    timeoutId = setTimeout(later, waitingTime);
  };
};

Now here `debounce` is a higher order function which is taking an actual function and waiting time and returning a another function. This is done to have closure on actual function and waiting time and timeoutId.

This debounce function can be use as


var debouncedFunction = debounce(
   () => console.log("Click event triggered"), 1000)

window.addEventListener("click", debouncedFunction);

Whenever user will click on the window, function attached to the event will not be executed instantly. This debounce function will wait for 1 second to listen if this function gets invoke again and if it does not then function will be executed after 1 second or if user clicks again within 1 second then countdown timer gets reset and debounce function will again wait for another 1 second to execute this function by scrapping the previous function call by using clearTimeout function with help of timeoutId of previous function.

Throttling

What is 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, only the first fire event executed immediately.

Throttling gives us a control over the rate at which function is executed, with this we can optimize the performance of the app by limiting calls per interval.

How exactly this technique behaves:

Suppose we have set time interval of 3 second for throttling, once the function is called for first time it gets executed immediately and timer starts for 3 second, within this waiting time if function is called again then it does not get executed. Next function execution will happen only after 3 second are elapsed. This is how we can control rate of function execution.

But this above explanation is not complete, what if the event is fired at 2nd second and it has not been executed, so will it be execute when timer ends? Answer is Yes! function executes after the timer ends if its been called again in waiting period. The idea of throttling is to execute function once after fixed time interval.

Throttling implementation in plain Javascript:

function throttle(callback, limit) {
  var wait = false;                 // Initially, we're not waiting
  return function () {              // We return a throttled function
    if (!wait) {                    // If we're not waiting
      callback.call();              // Execute users function
      wait = true;                  // Prevent future invocations
      setTimeout(function () {      // After a period of time
	      wait = false;               // And allow future invocations
      }, limit);
    }
  };
}

Conclusion

Debouncing and Throttling are just concepts or techniques can be use for solving specific set of problems, hence they are not provided by JavaScript itself. I am not giving here use case scenarios because I do not wish to limit one’s thinking to just finite set of use cases. This concepts are abstract and can be use to solve problems from various domains.

Intention of writing this article was give you more clearer explanations of this two techniques, for which I struggled a lot to wrap my head around. Criticism is always welcome!