Introduction To Throttling Using JavaScript
Improve your web applications’ performance via throttling technique in JavaScript
Another optimisation technique that really enhance performance of web applications is Throttling. This technique is specifically used in the browser to limit the amount of events a code handles unlike my previous blog post.
Throttling is used when a code needs to run a callback at a controlled rate, it allows you to handle intermediate states repeatedly at each fixed interval of time. One of the real life use case for this technique would be is that you might like to perform heavy operations or calculations or you might make several API requests in the event handler callback functions. You might throttle them out to prevent the app from freezing or unnecessarily making hundreds of requests to server.
Let’s get started with some code.
In above code, when user scrolls down on every pixel the callback noThrottle function will be called with no delay. This really is inefficient approach to handle scrolling scenarios. To make it more performant, let’s introduce throttling concept. Have a look at below code.
In above codebase, I created a throttle function which handles the throttling concept. Inside that function, I am declaring two variables i.e. timeout and cachedEvent. As you can see these variables are closured and will be shared among all events that are handled by throttle. eventHandlerFunction handles events and throttle callbacks if the throttle is active. Next, if throttle is inactive then execute the callback with lines 8 and 10. On line 15 we execute our throttle if there is a cached event.
Throttle Utility Libraries
There are few utility libraries that offers throttle functions but the best I have come across is lodash.throttle. It is a utility function implemented in lodash library. We can easily download that as an npm package with below yarn command.
Below is the way to use it.
That is it for this blog post. I hope you like it and if you do then go ahead and share it. If you have any questions or would like to add something then don’t forget comment below. See you next time.