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.
Top comments (2)
What would make you decide to use one over the other?
That totally depends on scenario we need to use.
For example,