Open In App

Underscore.js _.debounce() Function

Last Updated : 10 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Underscore.js _.debounce() Function in Underscore.js is used to create a debounced function that is used to delay the execution of the given function until after the given wait time in milliseconds has passed since the last time this function was called. The debounced function has a cancel method that can be used to cancel the function calls that are delayed and a flush method which is used to immediately call the delayed function.

Syntax:

_.debounce( function, wait, immediate );

Parameter:

  • function: It is the function that has to be debounced.
  • wait: It is the number of milliseconds for which the calls are to be delayed. It is an optional parameter. The default value is 0.
  • immediate: It is the boolean that specifies that the debounced function would be called at the beginning of the sequence instead of the end. It is an optional parameter.

Return Value:

This method returns the new debounced function.

Example 1: The example illustrates the  _.debounce() function is Underscore.js.

HTML




<html>
    
<head>
    <script src=
    </script>
</head>
    
<body>
    <h1 style="color: green">GeeksforGeeks</h1>
    <h3>Underscore _.debounce() Function</h3>
    <button onclick="debounce_fn()">
        Click to debounce function
    </button>
     
    <script type="text/javascript">
         let debounce_fn =
           _.debounce(debounceHandler, 2000, false);
          
         function debounceHandler() {
            console.log('Hello Geeks!')
         }
    </script>
</body>
    
</html>


Output:

Example 2: The example illustrates the  _.debounce() function is Underscore.js.

HTML




<html>
    
<head>
    <script src=
    </script>
</head>
    
<body>
    <h1 style="color: green">GeeksforGeeks</h1>
    <h3>Underscore _.debounce() Function</h3>
    <button onclick="debounce_fn()">
        Click to debounce function
    </button>
     
    <script type="text/javascript">
         let debounce_fn =
           _.debounce(debounceHandler, 2000, true);
          
         function debounceHandler() {
            console.log('Hello Geeks Immediately!')
         }
    </script>
</body>
    
</html>


Output:

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads