How to debounce function invocation in JavaScript | Lodash Library

4 years ago Lalit Bhagtani 0

JavaScript Debounce function invocation

In this tutorial, we will learn about how to debounce function invocation in JavaScript.

JavaScript Debounce

Debounce :-

The Debounce is a technique to group multiple sequential events calls into one event call. This technique is used to handle a scenario, where the user is creating a large number of same events by performing the same type of actions in very quick succession. 

Lodash debounce method :-

The debounce method creates a debounced function that delays the invoking of function until wait (provided as an option in milliseconds) time has elapsed, since the last time the debounced function was invoked.

Syntax :-

debounce(function, [wait=0], [options={[leading | trailing | maxWait]}])

where :
function : The function to debounce.
wait : The number of milliseconds to delay.
options : The object to pass leading, trailing and maxWait options.

The debounce method provides three options to configure the debouncing effect :

  1. leading: If true, then function is invoked on the leading edge of the wait timeout.
  2. trailing: If true, then function is invoked on the trailing edge of the wait timeout
  3. maxWait: The maximum time function is allowed to be delayed before it’s invoked.

The function is invoked with the last arguments provided to the debounced function. Subsequent calls to the debounced function return the result of the last function invocation.

The debounced function comes with a cancel method to cancel delayed function invocation and a flush method to immediately invoke it.

Use Case :-

A user types its password into an input box and on each keystroke, isPasswordValid function is invoked to check if the password contains at least 8 characters. If isPasswordValid function is called on onKeydown event listener, then this function will be called multiple times in quick succession as a user is typing on keyboard. Checking the length of the password before the user finishes its typing is useless. Hence, if we can defer the invocation of isPasswordValid function by using debounce technique so that it is invoked only when the user finishes typing its password can improve the overall performance of our user interface.

Let’s see the example :- 

1

References :- 

  1. Lodash debounce Docs

That’s all for how to debounce function invocation in JavaScript. If you liked it, please share your thoughts in comments section and share it with others too.