JavaScript Throttling

You must have noticed the efficiency of the web application's functionalities or how web applications handle user events. JavaScript Throttling or JavaScript Throttle concept provides the mechanism to improve the performance and speed of the application.

The throttling mechanism is also known as throttle method is a way to execute a function after a fixed interval after the first event is beig triggered by that function.

In this tutorial, we will discuss the concept of throttling, its use cases, and how it can enhance application performance. We will also discuss the scenarios if we don't use the Throttling. We will also explore the different ways to implement Throttling in our application. Also, There are multiple open-source libraries that offer throttling utility functions. we will also discuss them. So, let's start with what Throttling is and why we need this concept.

We will discuss the following topics:

  • What is Throttling in JavaScript?
  • Why use Throttling in JavaScript?
  • How does Throttling work in JavaScript?
  • Use cases for Throttling
  • Difference between Throttling and Debouncing

What is Throttling in JavaScript?

JavaScript Throttling is a mechanism that allows a function execution for a limited number of times after that it will block its execution. It can also prohibit a function from execution if it is invoked recently. It also determines a consistent rate of execution. It is a practice used in the web developed to enhance the application performance and prevent unexpected re-renders.

A great example of Throttling is assuming you have developed a game application with so many tournaments running, but you want a user to join a contest only once an hour. Then you can limit the content access for that specific user by using the throttling mechanism. If the user has triggered that event in the past hour, we can reject his request. No matter how many times he tries to request, the throttling mechanism will block him repeatedly until the defined time frame is complete.

It is known as Throttling. We are rate-limiting execution of a function over a while, in this case, one hour, to allow the user to join the contest.

Why use Throttling in JavaScript?

JavaScript Throttling can enhance the application's performance by applying the predetermined rate of function execution.

A Throttle function generates the function's call at a fixed time interval rate, preventing the app from lagging or overloading application. Hence, the server will respond to the requests sequentially and at a fixed time.

How does Throttling work in JavaScript?

Let's consider an example to understand JavaScript and how throttling works. Let's consider a scenario, we have added a scroll event listener to a web page, and it is customized in way that if a user scrolls, he will see some specific information. But, here, the problem is when the user scrolls frequently, sooner the web page will trigger more than hundreds of events. So, to resolve this problem, we will throttle the event in such a way we only call an event after a second of the previous event. This will result in only one callback per second. The user will feel the same result, but it will be far more computationally efficient.

Let's understand it with the help of the below example. In the belo example, we will use the throttle mechanism to understand the difference between the Throttling and non-throttling events.

Without using Throttling:

In the below example, the button is clicked ten times; consequently, the function will be clicked ten times. This is controlled by a throttling function.

Test.html:

Output:

JavaScript Throttling

From the above output, we can see the button clicked ten times then the event is triggered ten times.

Now, see the same example using the throttling approach:

In the above example, we are using the JavaScript throttling approach.

This above code specifies a button having an ID of "throt_evt". We are adding a click event listener to the button, which will be triggered when the button is clicked.

In the "myFunction" we are taking two parameters. The first paramerer is a function to be executed and the second parameter is a delay time which is in milliseconds.

In the above function, we are keeping the previous time value. This function will be executed under the condition if the difference between the previous time and the current time, is greater than the specified delay time.

The above function will log the message "clicked" to the console when the button is clicked and a delay time of 1000 milliseconds (1 second).

Consider the below output:

Output:

JavaScript Throttling

We can see from the above output if the previous time is greater than 1 ms, then it is logging the "clicked".

The above approach is called JavaScript throttling approach.

Use cases for Throttling

A throttle function executes the function at a predetermined rate and prevents the app from lagging or overloading the server while performing a time-consuming process or request. Below are some common use cases of a throttle function.

In Gaming

In games, a player needs to push the button to trigger any action, such as punching, shooting but during playtime, the user can hit the button more than one time in a second, and we want to trigger an action at the rate per second then the concept of Throttling will be useful for it.

Scroll event listeners

Most of the time, we use the scroll event handlers for specifying some operations and keeping track of the scroll positions. Generally, the scroll event handlers are used to load or animate some content.

To properly act on these events, we need to limit the user actions because if the user scrolls too frequently, it may have a negative impact on the application performance. In such cases, we must follow the throttling approach to display user data effectively.

Button click listeners

Throttling must be implemented to the click events for any specific operations. Like the ATM machine example, there is a fixed period for a transaction to be completed. Till then, we can not trigger any other new event. We can also apply it to the web application to limit the user event, and the callback function will only run after a certain period of time. It will help the user to display the proper output and avoid spam clicking.

Pointer events

We can also implement the throttling concept in pointer events like other events. The pointer events are similar to the scroll events. In such events, the user may frequently go in and out the mouse pointer, and the event will be triggered every time, so we can limit the pointer-events to avoid any unexpected output.

The mouse move and other pointer events are commonly used for tracking the cursor position. We may animate some stuff on our webpage as per the current mouse position. Thus, we can restrict a large number of calls for the callback invocations.

API calls

It is important to restrict the events for a specific time in API calls. The over-request of the API calls may affect the page load time. Thus, in some cases, we want to limit our application to external API calls.

In such cases, the Throttling can be very advantageous. Fixing the rate of the API calls, it will avoid unnecessary requests to the server.

Difference between Throttling and Debouncing

Debouncing and Throttling are very simple yet powerful techniques to improve the application performance.

We have discussed the Throttling in JavaScript. Let's understand what is debouncing then we will understand their key differences.

What is Debouncing

The main concept behind debouncing is to prevent unnecessary function invocations by delaying them for a specified period. Ensure the specified function is invoked only when no new event is triggered. If the user triggers a new event within the specified delay time, the timer will be reset.

Consider an example where we need to call an API for fetching the data, so their multiple-time event triggers may cause issues. We can avoid such issues by implementing a debouncing technique with some delay time.

In such cases, the user triggers an event within the specified time frame; the function will reset the delay time and wait for a specified time before making the API call.

The debouncing approach can be easily implemented using the setTimeout() and clearTimeout() functions. For implementing this approach, the function should take a callback function and the delay as input parameters.

Consider the below example:

In the above example, we can see myFunction is used as a wrapper for the callback function to ensure that it will be invoked after a delay time of 1s by default.

So the difference between debouncing and throttling is debouncing delays the execution of a function for a specified period until it has elapsed without making any further function calls; comparatively, throttling limits the number of times for a function to be called within a fixed period.

Now, let's understand some head-to-head comparisons of debouncing and Throttling.

Debounce VS Throttle

DebounceThrottle
Timingit delays the function invocation until a certain time has passed without any new events.It limits the frequency of function invocations to a set interval.
FunctionalityIt ensures that a function is only executed again once after a certain period has elapsed since the last execution of the function.It ensures that a function is executed at a regular interval, regardless of how many times it has been called.
DelayIt may use a delay in the execution of the function, as it waits for a specified period without new events.It may use a delay between function calls if the interval is set to a longer duration.
ResetIt resets the timer if a new event occurs within the specified delay period.It does not reset the interval, and the function will be called at the next interval, regardless of the number of events that occurred in the previous interval.
PurposeIt prevents a function from being executed too many times in response to user events.It limits the frequency of function calls responding to high-frequency events such as mouse movements or keystrokes.

Summary:

JavaScript Throttling is a mechanism that limits the function execution for a limited number of times. It ensures that a function is executed at a regular interval, regardless of how many times it has been called.

Comparatively, debouncing is a different approach used to prevent unnecessary function invocations by delaying them for a specified period.


Next TopicPolyFill JS




Latest Courses