DEV Community

Cover image for Understanding Throttling in JavaScript
Dipak Ahirav
Dipak Ahirav

Posted on

Understanding Throttling in JavaScript

Throttling is a technique in programming to ensure that a function is executed at most once in a specified time interval. This is particularly useful for controlling events that trigger multiple times in quick succession, like window resizing, scrolling, or mouse movements.

please subscribe to my YouTube channel to support my channel and get more web development tutorials.

What is Throttling?

Throttling ensures that a function is called at most once every specified interval. Unlike debouncing, which only executes the function after a delay period has passed since the last event, throttling ensures that the function is executed at regular intervals regardless of how many times the event is triggered.

Why Use Throttling?

  • Performance Enhancement: Reduces the number of function executions, preventing potential performance bottlenecks.
  • Resource Management: Helps in managing resource-intensive tasks by limiting their frequency.
  • Consistent Updates: Ensures regular updates at specified intervals, useful for tasks like updating a position indicator during scrolling.

How Throttling Works

Consider a scenario where you want to track the position of a user scrolling through a page. Without throttling, the position tracking function could be called hundreds of times per second, overwhelming the browser. Throttling helps by limiting the function call to a fixed interval, such as once every 100 milliseconds.

Implementing Throttling in JavaScript

Here is a simple implementation of a throttle function:

function throttle(func, limit) {
    let lastFunc;
    let lastRan;
    return function(...args) {
        const context = this;
        if (!lastRan) {
            func.apply(context, args);
            lastRan = Date.now();
        } else {
            clearTimeout(lastFunc);
            lastFunc = setTimeout(function() {
                if ((Date.now() - lastRan) >= limit) {
                    func.apply(context, args);
                    lastRan = Date.now();
                }
            }, limit - (Date.now() - lastRan));
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Usage Example

Let's see how we can use the throttle function in a real-world scenario:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Throttling Example</title>
    <style>
        body {
            height: 2000px;
            margin: 0;
            padding: 0;
        }
        .indicator {
            position: fixed;
            top: 10px;
            left: 10px;
            background: #333;
            color: #fff;
            padding: 10px;
        }
    </style>
</head>
<body>
    <div class="indicator" id="scrollIndicator">Scroll Position: 0</div>

    <script>
        const scrollIndicator = document.getElementById('scrollIndicator');

        function updateScrollIndicator() {
            scrollIndicator.textContent = `Scroll Position: ${window.scrollY}`;
        }

        const throttledUpdateScrollIndicator = throttle(updateScrollIndicator, 200);

        window.addEventListener('scroll', throttledUpdateScrollIndicator);

        function throttle(func, limit) {
            let lastFunc;
            let lastRan;
            return function(...args) {
                const context = this;
                if (!lastRan) {
                    func.apply(context, args);
                    lastRan = Date.now();
                } else {
                    clearTimeout(lastFunc);
                    lastFunc = setTimeout(function() {
                        if ((Date.now() - lastRan) >= limit) {
                            func.apply(context, args);
                            lastRan = Date.now();
                        }
                    }, limit - (Date.now() - lastRan));
                }
            }
        }
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In this example:

  • An indicator displays the current scroll position of the window.
  • The updateScrollIndicator function updates the position of the scroll indicator.
  • The throttledUpdateScrollIndicator function is created using the throttle function with a limit of 200 milliseconds.
  • The scroll event listener triggers the throttled function, ensuring that the position is updated at most once every 200 milliseconds.

Conclusion

Throttling is a powerful technique for optimizing web applications by controlling the frequency of function executions. By ensuring functions are called at regular intervals, throttling helps manage performance and resource usage effectively. Whether dealing with scrolling, resizing, or other rapid events, throttling is an essential tool in your JavaScript toolkit.

Follow me for more tutorials and tips on web development. Feel free to leave comments or questions below!

Follow and Subscribe:

Top comments (0)