Throttling and debouncing: When and How to use?

Throttling and debouncing: When and How to use?

Photo by olia danilevich

Throttling and debouncing refer to the technique used in the browser by limiting the number of events that will be executed. This is used to improve the performance of the website by reducing the number of events and preventing the application to freeze.
These are just the concepts to enhance the application performance and JavaScript doesn't provide any built-in method for these but we can have our own custom methods for this purpose. Now Let's understand both in detail, they might seem to be similar in their execution but are they?

Photo from Devsday.ru

Debouncing

Debouncing is a technique used where we care about only the final state of the event or the Event will be executed only after a certain period of inactivity. This is best suited for the use case of searching where we need to filter the result based on the search text.
Instead of making a search request while the user is typing, We can wait a certain milliseconds duration until the user is finished typing and this can avoid unnecessarily hammering the server with the search request and certainly improve the application performance.
Now comes the Implementation part of this concept and this is also a popular interview question to create your own debounce function. As It checks your understanding of your advanced javascript concepts such as async code, closure, scope, callback, and high-order functions.

// debounce takes the callback and delay and returns the function which will execute the callback function after `delay` seconds of inactivity.
function debounce(cb,delay){
    let timer=null;
  return function(){
    if(timer)
    // clear the timeout first for 
    clearTimeout(timer);
    // this will execute the callback after the timeout
      timer=setTimeout(()=>{
        cb();
      },delay*1000);
  }
}

Throttling

Throttling is also used to control the limit rate of event execution and it executes the callback on certain frequency intervals irrespective of the user's action to stop(let's say each second it will execute the throttle function ignoring the rest of the function calls in between).
It is mostly used in scenarios like events based on scrolling where we want to execute the events in a controlled manner instead of waiting for the user action to finish.

function throttle(cb,delay){
  let shouldExecute=true;
  return function(){
    if(shouldExecute){
    // callback is immediately invoked first and then timeout is set
      cb();
      shouldExecute=false;
        // purpose of this is to mark the time period complete
      setTimeout(()=>{
        shouldExecute=true;
      },delay*1000)
    }
  }
}
const throttleFunction = throttle(()=>console.log("Executed at:",new Date().getSeconds()),2);
window.addEventListener('scroll',throttleFunction);

Conclusion

Both throttling and debouncing are used for controlling the rate of event execution and hence improving the application performance significantly. In a nutshell, The main difference is that debounce method execution is delay based, and the throttle is frequency based.