paint-brush
Optimizing Performance With Throttling in JavaScriptby@marat
1,724 reads
1,724 reads

Optimizing Performance With Throttling in JavaScript

by Marat3mJanuary 5th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Some browser events have an extremely high-frequency rate. The number of events such as cursor moving, scrolling, resizing the browser window, holding down a key, etc., can reach 100 times per second. To reduce the load on the browser, you need to use throttling. Throttling allows you to "slow down" the function, i.e. the function will be executed no more than once in the specified period.
featured image - Optimizing Performance With Throttling in JavaScript
Marat HackerNoon profile picture
0-item

Some browser events have an extremely high-frequency rate. The number of events such as cursor moving, scrolling, resizing the browser window, holding down a key, etc., can reach 100 times per second. Functions called at this frequency of events place a heavy load on the browser and it leads to a decrease in performance.


Let's code a simple window resize event handler as an example:


const handleResize = () => {
    const { innerHeigh, innerWidth } = window;
    console.log({ innerHeigh, innerWidth });
}

window.addEventListener('resize', handleResize)


Try running this code in your browser console and resizing the window, and you will see that this function is called dozens of times even at a small resizing.


Now imagine that the handleResize function has not only output to the console, but a series of operations with complex manipulations with the DOM: in this case, the browser response to rendering will slow down drastically. How can this process be optimized? To reduce the load on the browser, you need to use throttling.

How to use throttling?

Throttling allows you to "slow down" the function, i.e. the function will be executed no more than once in the specified period, even if it is called many times during this period. For example, if you set throttle with a time of 100ms on the page scroll event, then the function will be executed every 100ms while scrolling takes place.


Schematically, this can be displayed in the following way:


Many JavaScript libraries such as lodash, underscore, rxjs offer a throttle method with various additional features. Below you can read a fairly common implementation of the throttle method:


function throttle(fn, time) {
    let timeout = null;
    return function () {
        if(timeout) return;
        const context = this;
        const args = arguments;
        const later = () => {
            fn.call(context, ...args);
            timeout = null;
        }
        timeout = setTimeout(later, time);
    }
}


Let's go back to the example with the window resize event handler and see that the throttle handler is called much less frequently (set to 500ms for demonstration purposes):


const handleResize = () => {
    const { innerHeigh, innerWidth } = window;
    console.log({ innerHeigh, innerWidth });
}

const handleResizeThrottled = throttle(handleResize, 500);
 
window.addEventListener('resize', handleResizeThrottled);


Therefore, no matter how often some event is called, throttling will not allow the desired function to run too often and will decrease the load on the browser.

Conclusion

That's all I wanted to say about the throttle function. I hope you liked my article and found it useful.