Lodash _.debounce() Method
Last Updated : 09 Jan, 2025
The Lodash _.debounce() method is a utility function that delays the execution of a given function until a specified wait time has passed since the last invocation. This method is particularly useful in scenarios where events fire frequently, such as resizing, scrolling, or input events, helping prevent unnecessary or excessive function calls that can affect performance
How _.debounce() Works
_.debounce() creates a debounced version of a function, ensuring it is only called once after a certain wait period has elapsed since the last event. This helps manage rapid-fire events more efficiently, reducing the number of times the function is executed.
Lodash _.debounce() MethodSyntax
_.debounce( func, wait, options{})Parameters:
- func: 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.
- options: It is the options object that can be used for changing the behavior of the method. It is an optional parameter
- leading (boolean): If it is true the function will get executed immediately rather than waiting for the 'wait' time. The default value is false means it waits until the 'wait' time is not completed.
- maxWait (number): It is the maximum number of times, the function will be called after completion of this time.
- trailing (boolean): It defines the calling of a function to the specified time(wait time). by default, it sets to true.
Return Value: Returns a new debounced function
Understanding how to optimize performance with techniques like debouncing is essential for modern development.
Examples of Lodash _.debounce() Method
Example 1: In this example, the function will be called after 1000ms as mentioned in the lodash.debounce() function.
JavaScript // Requiring lodash library const lodash = require('lodash'); // Using lodash.debounce() method // with its parameters let debounce_fun = lodash.debounce(function () { console.log('Function debounced after 1000ms!'); }, 1000); debounce_fun(); Output:
Function debounced after 1000ms!
Example 2: In this example, both optional parameters are true that's why function is executing immediately without following the specified time.
JavaScript // Requiring lodash library const _ = require('lodash'); // Using _.debounce() method // with its parameters let debounced_fun = _.debounce(function () { console.log("function is executing immideately!!") }, 5000, { leading: true, trailing: true }); debounced_fun(); Output:
function is executing immideately!!
Explore
JavaScript Basics
Array & String
Function & Object
OOP
Asynchronous JavaScript
Exception Handling
DOM
Advanced Topics
My Profile