Open In App

Underscore.js _.throttle() Function

Last Updated : 02 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

  • function:  It is the function to be throttled.
  • wait: It is the number of milliseconds for which the calls are to be throttled.
  • options: It is the options object.
    • options.leading: It defines the calling on the leading edge of the timeout.
    • options.trailing: It defines the calling on the trailing edge of the timeout.

Return Value: This method returns the new throttled function.

 

Example 1:

HTML




<!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:

Underscore _.throttle() Function

Example 2:
 

HTML




<!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:

Underscore _.throttle() Function

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads