The Wayback Machine - https://web.archive.org/web/20250110072954/https://www.geeksforgeeks.org/javascript-throttling/
Open In App

JavaScript Throttling

Last Updated : 21 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JavaScript throttling limits the frequency at which a function is executed, ensuring it runs at most once in a specified time interval. It’s useful for optimizing performance in scenarios involving rapid, continuous events like scrolling or resizing.

What is Throttling?

Throttling is a technique that limits the frequency of function execution, allowing it to run at most once within a specified time interval. It’s used to optimize performance during events like scrolling, resizing, or clicking.

How to Implement Throttling in JavaScript

  • Create a Throttle Function: Define a function that takes a callback and delay to control execution frequency over time.
  • Track Last Execution Time: Store the timestamp of the last function execution to calculate if the delay has passed.
  • Check Time Interval: On each trigger, compare the current time with the last execution time; only execute if sufficient time passed.
  • Return Throttled Function: Return a new function that runs the original callback only when the time interval condition is met.

Without throttling Function:

Without throttling, a function may be invoked rapidly, leading to performance issues, unnecessary resource consumption, and a potentially poor user experience.

Example: In this example, we adds an event listener to a button without throttling. Each click triggers the callback immediately, logging ‘button is clicked’ to the console without any rate limitation.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
    content="width=device-width, 
    initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button id="nothrottle">Click Me</button>
    <script>
        // Selected button with the given id
        const btn = document.
        querySelector("#nothrottle");

        // Add event listener to the button 
        // to listen the click event
        btn.addEventListener("click", () => {
            console.log("button is clicked");
        });
    </script>

</body>

</html>

Output:

With Throttling function:

With throttling, you limit the frequency of function invocations. For example, you might decide to execute a function at most once every 1500 milliseconds. This prevents the function from being called too frequently and helps maintain a smoother performance.

Example: In this example, we adds throttling to a button click event, limiting the ‘button is clicked’ log to execute once every 1500 milliseconds, regardless of rapid clicks.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
    content="width=device-width, 
    initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button id="throttle">Click Me</button>
    <script>
        const btn = document.querySelector("#throttle");

        // Throttling Function
        const throttleFunction = (func, delay) => {

            // Previously called time of the function
            let prev = 0;
            return (...args) => {
                // Current called time of the function
                let now = new Date().getTime();

                // Logging the difference
                // between previously 
                // called and current called timings
                console.log(now - prev, delay);

                // If difference is greater
                // than delay call
                // the function again.
                if (now - prev > delay) {
                    prev = now;

                    // "..." is the spread
                    // operator here 
                    // returning the function with the 
                    // array of arguments
                    return func(...args);
                }
            }
        }
        btn.addEventListener("click",
            throttleFunction(() => {
                console.log("button is clicked")
            }, 1500));
    </script>

</body>

</html>

Output:

Advantages of throttling function: 

  • It prevents frequent calling of the function.
  • It makes the website faster and controls the rate at which a particular function is called.
  • Performance Optimization.
  • Improved Responsiveness.

JavaScript Throttling-FAQs

How do you implement throttling in JavaScript?

You can implement throttling using a custom function that tracks the last execution time and only allows execution if the specified delay has passed.

When should I use throttling in JavaScript?

Throttling is ideal for performance optimization in scenarios involving rapid, continuous events like scrolling, resizing, mouse movements, or button clicks.

How is throttling different from rate limiting?

Throttling limits how often a function is called within a set interval, while rate limiting restricts the total number of times an operation can be performed over a period (e.g., API calls).

What are common use cases for JavaScript throttling?

Throttling is commonly used in scenarios like handling scroll events, resizing windows, processing form inputs, and limiting click event handling.

Can throttling be combined with debouncing?

Yes, throttling and debouncing can be combined depending on the use case. For example, throttle the function while debouncing certain input events to get optimized control.



Next Article

Similar Reads

three90RightbarBannerImg