Open In App

Underscore.js _.throttle() Function

The _.throttle() method in underscore is used to create a throttled function that can only call the func parameter maximally once per every wait milliseconds. The throttled function 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 which are used to imply whether the func stated should be called on the leading and/or the trailing edge of the wait timeout.
Syntax:

_.throttle(function, wait, [options])

Parameters: The method accept three parameters as mentioned above and described below.



Return Value: This method returns the new throttled function.

 



Example 1:




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
</head>
  
<body>
    <center>
        <h1 style="color:green;">
            Geeksforgeeks
        </h1>
          
        <b>Underscore.js _.throttle() Method</b>
    </center>
  
    <script type="text/javascript">
          
        // Calling throttle() method with its parameter
        var gfg = _.throttle(function () {
            console.log('Function throttled after 1000ms!');
        }, 1000);
  
        gfg();
    </script>
</body>
  
</html>

Output:

Example 2:
 




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
</head>
  
<body>
    <center>
        <h1 style="color:green;">
            Geeksforgeeks
        </h1>
          
        <b>Underscore.js _.throttle() Method</b>
    </center>
  
    <script type="text/javascript">
      
        // Calling throttle() method with its parameter
        var throt_fun = _.throttle(function () {
            console.log('Function throttled after 1000ms!');
        }, 1000);
  
        // Defining loop
        var loop = function () {
            setTimeout(loop, 5)
            throt_fun();
        };
  
        // Calling loop to start
        loop();
    </script>
</body>
  
</html>

Output:

Reference: https://underscorejs.org/#throttle


Article Tags :