What are debounce and throttle in JavaScript?

3

I have seen that they are methods that are usually done by those who write JavaScript for help or for a specific purpose but I am not sure what each one does.

    
asked by José Gregorio Materán 07.02.2017 в 05:14
source

1 answer

4

Throttle sets a maximum number of executions per time interval. For example, it allows the execution of this function a maximum of once every 500 ms.

  

throttle (fn, wait, [options]) (translation)

     

Take a function as a parameter and return a new version of the   function that, when invoked repeatedly, will not run anymore   once for each wait in milliseconds.

Debounce sets a minimum time between executions. For example, execute this function with a minimum of 500 ms between consecutive executions.

  

debounce (fn, wait, [immediate]) (translation)

     

Take a function as a parameter and return a new version of the   function that, when invoked, will not be executed until there is   A wait time has elapsed in milliseconds.

     

This means that if the function is called in rapid succession   will be executed only once, when the avalanche has finished   of calls.

Notes:

  • throttle has changes in its functionality thanks to the options. By default the call is made the first time the function is called and an additional time after the waiting time, as would debounce . Setting to false the value of leading and / or trailing we can do not call the function immediately the first time or after the last time spent the waiting time.
  • debounce , on the other hand, has a unique change in its functionality through the immediate option, which makes the call immediately (instead of postponing it). It can be used, for example, to avoid sending a form because of a double click on a send button.
answered by 07.02.2017 в 12:17