Implement throttle using vanilla javascript

This one is pretty similar to the previous article where I wrote about debouncing. Let's as usual start by understanding what throttling is.

What's throttling in javascript?

Throttling is a technique used to control the rate at which certain events or actions can be performed. In JavaScript, throttling is often used to limit the number of times a function can be executed within a specific time frame. This technique helps to reduce the overall processing load on the server and improve the performance of the application.

Implementation using Javascript

JavaScript provides various methods to implement throttling, such as using the setTimeout function, the debounce function, or custom implementations. Here, we will discuss the implementation using the setTimeout function.

The setTimeout function is used to delay the execution of a function by a specified amount of time. We can use this function to implement throttling by setting a delay between the executions of a function. Here is an example of how to implement throttling using the setTimeout function:

function throttle(func, delay) {
  let timeoutId;
  return function(...args) {
    if (!timeoutId) {
      timeoutId = setTimeout(() => {
        func.apply(this, args);
        timeoutId = undefined;
      }, delay);
    }
  }
}

In the above code, we have defined a throttle function that takes two parameters: (1) the function to be throttled and (2) the delay between each execution. The throttle function returns a new function that implements the throttling logic. The new function takes any number of arguments and executes the throttled function only if the timeout has expired. If the timeout has not expired, the function simply returns without executing the throttled function.

The below example shows how to use the throttle function to throttle the execution of a function that logs a message to the console:

function logMessage() {
  console.log('Message logged');
}

const throttledLogMessage = throttle(logMessage, 1000);

throttledLogMessage();
throttledLogMessage();
throttledLogMessage();

In the above code, we have defined a logMessage function that logs a message to the console. We have then created a throttled version of this function using the throttle function with a delay of 1000 milliseconds which is named as throttledLogMessage. Finally, we have called the throttled version of the function three times in quick succession. Since the delay between each execution is 1000 milliseconds, only the first execution will log the message to the console, and the other two executions will be ignored.

You can use throttling for any operation that happens continuously and needs to be fine-tuned or restricted to make it happen only a certain number of times.

Common Use Cases of Throttling in Web

Throttling is commonly used in web development to improve the performance of the application and reduce the load on the server. Some common use cases of throttling in web development are:

  1. Scroll Event Throttling: In web applications, we often need to handle scroll events to perform certain actions. However, scroll events can be fired many times in quick succession, which can lead to performance issues. Throttling can be used to limit the rate at which scroll events are handled, thus reducing the load on the server.

  2. Search Input Throttling: When implementing search functionality in a web application, we need to handle user input in real-time. However, users can type very quickly, which can result in many requests being sent to the server. Throttling can be used to limit the rate at which the requests are made.

  3. Resize Event Throttling: When the user resizes the browser window, the resize event is fired multiple times. Handling each event can be costly in terms of performance, especially if the application involves complex calculations or rendering. Throttling can be used to handle resize events in a controlled and efficient manner.

  4. Button Click Throttling: In some cases, users may repeatedly click on a button, such as a submit button, resulting in multiple requests being sent to the server. Throttling can be used to limit the rate at which button clicks are handled, thus preventing multiple requests from being sent to the server.

  5. Mouse move Event Throttling: When the user moves the mouse, the mouse move event is fired multiple times. Handling each event can be costly in terms of performance, especially if the application involves complex calculations or rendering. Throttling can be used to handle mouse move events in a controlled and efficient manner.

  6. API Requests Throttling: When making requests to an API, it's important to manage the rate at which the requests are sent to avoid overwhelming the API server. Throttling can be used to limit the rate at which API requests are sent, ensuring that the server is not overloaded and that the application remains responsive.

  7. User Interface Animations Throttling: Animations in the user interface can be resource-intensive, especially if they involve complex graphics or transitions. Throttling can be used to control the rate at which animations are rendered, ensuring that they don't impact the performance of the application.

  8. ...

Great, throttling is a pretty useful technique to improve performance. But, debouncing also does similar things then what are the differences between the two, and when to use what?

Let's deep-dive more.

Debouncing vs Throttling in javascript

ThrottlingDebouncing
Execution TimingLimits the rate at which a function can be executed by setting a delay between each execution.Delays the execution of a function until a certain amount of time has passed without the event being fired again.
Event HandlingAllows events to be handled at a controlled and reduced rate.Ignores events until a certain amount of time has passed without any new events being fired.
Function CallEnsures that the function is called at a fixed interval.Ensures that the function is only called once after the specified time has elapsed.
Multiple CallsCan allow multiple calls of a function to be executed if they occur within the specified interval.Ensures that only the last call is executed after the specified time has elapsed.

Cool, now let's also understand when to use each of them.

When to throttle and when to debounce?

Knowing when to use throttling and when to use debouncing in JavaScript can be a bit tricky. It all comes down to the use case you're trying to solve. Both debounce and throttle utilities address a similar problem with slight variations in their approaches.

Let's take the example of a User scrolling the page. You can do both throttling and debouncing in this case.

But, if you want to change the position of some elements as the user scrolls, you would probably go for throttle as it gets fired at regular intervals even if the user still is scrolling. On the other hand, if you debounce for this particular use case, you would only see the element position getting changed after the user stopped/paused scrolling. This may not be the intended behavior.

Similarly, if you want to handle auto suggestions as the user is searching the search box, you would probably debounce as you would essentially want to let the user finish his query before making a request as the previous requests even if they are made are going to be invalid based on the new searches. throttle wouldn't help much in this particular case of suggesting.

I hope this article was helpful to you. If yes, please make sure to read my other articles. I am currently writing a series on common "Frontend engineering interview questions" based on my experience interviewing people at Amazon, RedHat, VMware, and Snapdeal, ...

Please subscribe to the newsletter to get the articles delivered directly to your mailbox.

#2Articles1Week

Cheers

Arunkumar Sri Sailapathi.