DEV Community

shifaligupta
shifaligupta

Posted on

Debouncing and Throttling

Debouncing and Throttling are two ways to optimize performance of web application by limiting rate of the execution of a function call. It is particularly useful when we are attaching function to DOM events, because in these scenarios we might be invoking unnecessary function calls.

Debouncing

The debounce pattern lets us control events that are triggered successively, and if the interval within two events is greater than a certain amount of time, only then the function is called.

Implementation

Debounce function takes two arguments - function and delay.
It does not let function make unnecessary calls again and again and will only make function call if the difference between time Intervals of function calls is greater than the delay.

Throttling

Throttling is a technique in which, no matter how many times the user fires the event, the next function call will be delayed for a certain time Interval.
It restricts the maximum number of times that a function can be called. This method is usually used to control window resizing, scrolling and mouse-related events.

Implementation

Throttling function takes two arguments - function and time Interval.
It will check the difference between last function call and the function call. If the difference between two function calls is a certain time, then only the function is called.

Oldest comments (2)

Collapse
 
tomdohnal profile image
Tom Dohnal

What would make you decide to use one over the other?

Collapse
 
shifaligupta profile image
shifaligupta

That totally depends on scenario we need to use.
For example,

  • We can throttle a button click event, if we do not want the user to spam by clicking the button frequently.
  • We can debounce mouse movement, if we are displaying the location coordinates of the mouse pointer as it is much better to show the coordinates once the user reached the desired location.