How to throttle function invocation in JavaScript | Lodash Library

4 years ago Lalit Bhagtani 0

JavaScript Throttle function invocation

In this tutorial, we will learn about how to throttle function invocation in JavaScript.

JavaScript Throttle

Throttle :-

The Throttle is a technique in which a function is executed only once in a given interval of time, even when it is invoked multiple times. For example, a user clicks a button multiple times in very quick succession, but the function attached to the click event will execute only once in a given interval of time.

Lodash throttle method :-

The throttle method creates a throttled function that invokes the function at most once in every wait (provided as an option in milliseconds) time. 

Syntax :-

throttle(function, [wait=0], [options={[leading | trailing]}])

where :
function : The function to throttle.
wait : The number of milliseconds to throttle the invocation of function.
options : The object to pass leading, trailing options.

The throttle method provides two options to configure the throttling effect :

  1. leading: If true, then function is invoked on the leading edge of the wait timeout.
  2. trailing: If true, then function is invoked on the trailing edge of the wait timeout.

The function is invoked with the last arguments provided to the throttle function. Subsequent calls to the throttled function return the result of the last function invocation.

The throttled function comes with a cancel method to cancel delayed function invocation and a flush method to immediately invoke it.

Use Case

There are many use cases of throttling technique, let’s see one of them :

Infinite Scrolling

A user is scrolling down your web page and when the user reaches the bottom of the page,an Ajax request should be fired to get the data from the backend and appended to the end of the page to make a feel like our web page is infinitely long.

A wrong way to implement this is by calculating the position of a user on every onscroll event and when a user reaches the bottom of the page, make ajax request. When a user scroll downs a page, it fires a large number of onscroll event and calculating the position of a user on each event can degrade the performance of your web page. Hence it will be a better approach to calculate the position only once in a specific interval of time over the course of onscroll action.

Let’s see the example:

1

References :- 

  1. Lodash throttle Docs

That’s all for how to throttle function invocation in JavaScript. If you liked it, please share your thoughts in comments section and share it with others too.