Open In App

Lodash _.throttle() Method

Lodash _.throttle() method is used to create a throttled function that can only call the func parameter maximally once per every wait milliseconds. The throttled function here has a cancel method which is used to cancel func calls that are delayed and it also has a flush method which is used to immediately call that delayed func.

Moreover, it provides some options that are used to imply whether the function stated should be called on the leading and/or the trailing edge of the wait timeout.



Syntax:

_.throttle(func, [wait=0], [options={}])

Parameters:

Return Value:

This method returns the new throttled function

Note:

Example 1: In this example, after the function is throttled after 1000ms the waiting time here is 1000ms.






// Requiring lodash library
const _ = require('lodash');
 
// Calling throttle() method with its parameter
let throt_fun = _.throttle(function () {
    console.log('Function throttled after 1000ms!');
}, 1000);
 
throt_fun();

Output:

Function throttled after 1000ms!

Example 2: In this example, after the function is throttled after 1000ms the waiting time here is 1000ms. So, here the loop doesn’t stop until you stop it manually.




// Requiring lodash library
const _ = require('lodash');
 
// Calling throttle() method with its parameter
let throt_fun = _.throttle(function () {
    console.log('Function throttled after 1000ms!');
}, 1000);
 
// Defining loop
let loop = function () {
    setTimeout(loop, 5)
    throt_fun();
};
 
// Calling loop to start
loop();

Output:

Function throttled after 1000ms!
Function throttled after 1000ms!
Function throttled after 1000ms!
Function throttled after 1000ms!
Function throttled after 1000ms!
Function throttled after 1000ms!
.
.
.
.
// So on until you stop it manually.

Example 3: In this example, the function is called on the trailing edge of the timeout.




// Requiring lodash library
const _ = require('lodash');
 
// Calling throttle() method with its parameter
let throt_fun = _.throttle(function () {
    console.log('Function is called on the'
        + ' trailing edge of the timeout '
        + 'and throttled after 2000ms!');
}, 2000, { 'trailing': true });
 
throt_fun();

Output:

Function is called on the trailing edge of the timeout and throttled after 2000ms!

Article Tags :