Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference Between throttling and debouncing a function

Tags:

javascript

Can anyone give me a in-simple-words explanation about the difference between throttling and debouncing a function for rate-limiting purposes.

To me both seems to do the same the thing. I have checked these two blogs to find out :

http://remysharp.com/2010/07/21/throttling-function-calls

http://benalman.com/projects/jquery-throttle-debounce-plugin/

like image 636
bhavya_w Avatar asked Sep 23 '14 09:09

bhavya_w


People also ask

What is a throttled function?

Throttling or sometimes is also called throttle function is a practice used in websites. To throttle a function means to ensure that the function is called at most once in a specified time period (for instance, once every 10 seconds). This means throttling will prevent a function from running if it has run “recently”.

What is a debounce function?

The debounce() function forces a function to wait a certain amount of time before running again. The function is built to limit the number of times a function is called. The Send Request() function is debounced. Requests are sent only after fixed time intervals regardless of how many times the user presses the button.

What is throttle function in Javascript?

Throttling or sometimes is also called throttle function is a practice used in websites. Throttling is used to call a function after every millisecond or a particular interval of time only the first click is executed immediately.

What is the difference between Debounce and setTimeout?

debounce uses setTimeout internally so the difference is related to the number of times setTimeout is fired. debounce throttles the amount of times it fires setTimeout . If multiple requests are sent in a short duration, only one will come through.


1 Answers

To put it in simple terms:

  • Throttling will delay executing a function. It will reduce the notifications of an event that fires multiple times.
  • Debouncing will bunch a series of sequential calls to a function into a single call to that function. It ensures that one notification is made for an event that fires multiple times.

You can visually see the difference here

If you have a function that gets called a lot - for example when a resize or mouse move event occurs, it can be called a lot of times. If you don't want this behaviour, you can Throttle it so that the function is called at regular intervals. Debouncing will mean it is called at the end (or start) of a bunch of events.

like image 61
Donal Avatar answered Sep 20 '22 05:09

Donal