Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between throttleTime vs debounceTime in RxJS and when to choose which?

Tags:

I'm trying to understand throttleTime vs debounceTime and which one is to be used when?

I have an upvote button that makes an API request to the backend (which counts the votes). User can submit button multiple times, but I'd like to limit the times per second button can be pressed.

I know throttleTime and debounceTime operators can do that, but which one should I choose?

const upvoteClicks = fromEvent(this.el.nativeElement, 'click')    .pipe(debounceTime(500))    .subscribe(() => this.myService.postUpvote(this.postId)); 
like image 527
Cleave Kokle Avatar asked Jun 05 '19 12:06

Cleave Kokle


People also ask

What is throttleTime in RXJS?

throttleTime emits the source Observable values on the output Observable when its internal timer is disabled, and ignores source values when the timer is enabled. Initially, the timer is disabled. As soon as the first source value arrives, it is forwarded to the output Observable, and then the timer is enabled.

What is the difference between debounce time and throttle time?

# Throttling tells us the maximum number of times a function can be called over a period of time. It executes the function once every 100 milliseconds. # Debouncing means that a function will not be called again until a certain amount of time has passed without it being called.


1 Answers

I think in your case throttleTime works a little bit better, because you want to make the api request as soon as user clicks the button.

Both throttleTime and debounceTime ignore the events which come in the meantime, but throttleTime emits right away, while debounceTime waits for additional delay.

You can visually see that very well at https://rxmarbles.com enter image description here

enter image description here

What is more, throttleTime vs debounceTime in RxJS article provides a good overview of both operators.

like image 148
Harijs Deksnis Avatar answered Sep 23 '22 22:09

Harijs Deksnis