Debouncing and Throttling: InterviewP1👩🏾‍💻

Debouncing and Throttling: InterviewP1👩🏾‍💻

Intro:🧿

Hello guys,😎 I'm back with new series on Interview topics and terminologies.🆒 These topics are picked as per their popularity🦸🏾‍♂️ and usefulness as they are used in the daily life code of the Frontend Coders and Developers.👩🏾‍💻

And, yeah Chubby🙋🏽‍♂️ will again be our partner in this blog read. Say Hi to Chubby👼🏾.

🙋🏽‍♂️ this blog also contains funny memes like other? Yeah Chubby, we will see some in the last para, first concentrate on the intro of this blog.💈

In this blog, we are going to talk about debouncing and throttling. Both of them are used to limit the rate of function execution in the code. By using one of these techniques, we can reduce the call load of the function and improve its performance. So through this, we control the rate of function execution over time.

🙋🏽‍♂️I didn't get it...🙄 Wait Chubby, let me explain one by one to make it more clear. ok?🆗 For that first understand where we use these techniques.

Event Listeners🤳🏾 and Function Executions:🏋🏾‍♀️

In a function, we attach some event handlers which handle the activities which are listened to by the event listeners. These listeners are attached to buttons, mouse🐭 movements, key movements, hover events💫 etc. We as a developer have to listen to all those activities which we can use to make the website functional and responsive.

However, as a developer most of the time we decide when we execute any event, but when there are too many events occurring simultaneously and we can't pinpoint when to execute the event handler function, then we use rate limiters to reduce the rate of event execution per event.

🙋🏽‍♂️Ohh everything went over my head...🤯

Let's understand it with an example. If we are listening to the search bar /input field where user put their query to search username. If we just listen to the inputs without any rate limiter, our function will execute on every key press 👇🏻. That will trigger the search algorithm to find the query got as input. That will be very inefficient. 🙋🏽‍♂️How??

Chubby, if we call our event handler function which contains the search algorithm on every keystroke, it will start executing quickly🏃🏾‍♂️ and it will take some bandwidth and processes. And also the result we get from that search will also be not very accurate as it comes out from an incomplete query. Similarly, all those events perform heavy🏋🏾‍♀️ computations, and the algorithm runs and result in a high response time in each call. Here we have to restrict the call rates by rate limiters.✋🏽

🙋🏽‍♂️So we should wait till the user complete its query so that the search algorithm comes up with the best result?? Yes Chubby, 👏🏻now you're getting my point. So do you know how we wait for the user to finish their query? 🤷🏽‍♂️No! I also don't know 🤷🏽‍♂️hahaha... We can't predict how long the user will write their query on the search bar. So we use Debouncing and Throttling techniques for that.

Debouncing:☔

In this technique, we can stop or delay the execution event until the user has stopped the triggering events for a specified time interval.🧭 We set some timeout where function execution will wait till the last event occur.

For example, most blogging and MS word save the text as we write. It also has some timeout between saving the text and the last text letter entered. Hashnode Blog page also has this functionality where it saves the text only after a fraction of the delay in typing. If we type non-stop like ChatGPT❄, then it will wait till it completes the writing.

In Codes:

      let count = 0; // will count the number of network calls on events
      function work() {
        console.log("Network Call", count);
        count++;       
      }
      // Debouncing is performed
      function debouncing(work, delay) {
        let timerId;
        return function optWorkFn() {
          clearTimeout(timerId); // will act as rate limiter and clear the timer if delay does not reach to the next keypress. Timeouts are not allowed till keypress give the delay time. Network call will be done only when delay is reached. if user is like computer and do not give delay for long time, it will wait for the delay for long time. and when it get the delay it will immediately call the network.
          timerId = setTimeout(() => {
            work();
          }, delay);
        };
      }

      let optimizedFunction = debouncing(work, 500); // got the work and delay of 500ms.
      const input = document.querySelector("input");
      input.addEventListener("keydown", optimizedFunction);

This work() is our Network call, which we have to restrict from calling frequently.✋🏽 If we call this function directly in the eventListener, it will call on every keypress event.🤹🏽‍♂️ This will be very costly and inefficient. So we need an optimized function that will call only when it is needed. Hence we changed that event handler function with our optimized function.

Hence our ClearTimeOut will act as a rate limiter and save the execution of the function when the delay equates with the delay prescribed.

Throttling:🚥

So, we know how to wait for any event to occur. But we can't wait all day if the user does not query anything or just type texts non-stop.🖨 We have to call the event handler after some specific time even if events are happening simultaneously. 🙋🏽‍♂️Why?

We can't leave out our page empty without any data.🗑 We have to fetch some data from the network call for the first time and also make consistent calls so that our page does not remain idle and get outdated. Here we use Throttling. 🧿

In Throttling, it continuously executes the event handler function as the event occurs simultaneously. The rate depends on the delay set for the execution. If the user does not do anything it will just be executed for the first time only. But if the user gives too many inputs, it will just keep on executing the calls at regular intervals which will be simultaneous to the events. When the last event occurs, execution also terminates ✋🏽the call after the specified time delay.

In codes:

let count = 0; // will count the number of network calls on events
      function work() {
        console.log("Network Call", count);
        count++;
      }
// throttling is performed
      function throttling(work, delay) {
        let flag = true; // true for first call
        return function optWorkFn() {
          if (flag === true) {
            work();
            flag = false;
            // wait for timeout for to get the flag set to true, till then it will wait. Hence here rate limit is based on the interval of delay provided. Its network calling will be consecutive and does not depend on the user input.
            setTimeout(() => {
              flag = true;
            }, delay);
          }
        };
      }
      let optimizedFunction = throttling(work, 500); // got the work and delay of 500ms.

      const input = document.querySelector("input");
      input.addEventListener("keydown", optimizedFunction);

So, it does not depend on the🦸🏾‍♂️ user input event for the executions of the event handler.

🙋🏽‍♂️Which one is better? Since both techniques tackle different problems and are based on different concepts, so there is no comparison on superiority. We can see some differences and their use cases and then decide where we can use them and make our program more efficient.

Difference between these techniques🤼‍♂️

DebouncingThrottling
It depends on the user's inputIt does not depend on the user's input
Executions per event are irregularExecutions per event are regular and consecutive
It limits the rate by combining the input packetIt limits the rate by executing only specified delay without concern for the user input.

Use cases of Debouncing and Throttling:🛒

  1. API throttling: API throttling is the process of limiting the number of API requests a user can make in a certain period. Organizations use API throttling with various goals, such as security, scalability, performance, monetization, authentication, and availability. https://www.tibco.com/reference-center/what-is-api-throttling

  2. Click events in the Payment section. For a website that has a submit button to place an order, if a user double-clicks the button, they may accidentally buy the order twice. A debounce function would ensure that only one request is submitted.

  3. For Autofill and Search box: Debounce can ensure that the input was accepted only after every letter was typed into the box. Other activations could cause poor performance, high server load or user confusion. A debounce function might wait for a second or two after the last letter is typed before taking any action.

  4. On Mouse Movement: like a graphic element or message that's programmed to follow the cursor around the screen or as a webpage is scrolled through. This action could run hundreds of times a second and cause poor page performance or high resource utilization. A debounce function could limit the movement script to only run a few times a second to maintain smooth performance.

https://www.techtarget.com/whatis/definition/debouncing

  1. Measure the scroll position of the page: The browser will fire the scroll binding event every single time the user scrolls, which can result in many events per scroll. If the binding event performs several repaints, this spells bad news for the end user; layout reflows and repaints are expensive, especially when you are redrawing large parts of the view, as is the case when there is an scroll event.

  2. Wait until the user stops resizing the window: Window resizes operations cause various child elements to update themselves by resizing and re-organizing themselves. By throttling, you can delay the resizing events and fire fewer of those resizing events.

  3. Fire Ajax calls under control and avoids unnecessary network request handling: for example, in case of searching for external data, wait until the end-user stops typing by using debounce. If you are sending log data frequently, use the throttle.

How to decide when to use these techniques?🤷🏽‍♂️

I recommend looking at the problem from the end-userʼs perspective (it may be a performance problem, a user-experience problem, or something else altogether) to understand which technique to use. Does the end-user need things to happen right away (hinting at the throttle)? Just once (hinting at debounce)? Or maybe every 500ms?

Meme Time:

So, Chubby it's your time to pitch. Ok

If you like the blog, please like and also comment about your feeling towards debouncing. If your preparing for interviews and stuff, let's connect on LinkedIn and Discord with the same username: Rahul4dev