Cleave Kokle
Cleave Kokle

Reputation: 413

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

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));

Upvotes: 39

Views: 25470

Answers (3)

KienHT
KienHT

Reputation: 1346

The accepted answer has clearly pointed out the difference between throttleTime and debounceTime.

However I'd like to bring up a slightly different option in your particular situation, that is exhaustMap. exhaustMap is an operator that ignores every new projected Observable if the previous one has not yet completed. So the first API request to backend has to be completed before the user can execute it the second time. It's useful if the API data is bouncing back very slowly, slower than the fixed time you set, it won't trigger any further API call until the previous one completed. You can read more about exhaustMap here.

const upvoteClicks = fromEvent(this.el.nativeElement, 'click')
   .pipe(
      exhaustMap(() => this.myService.postUpvote(this.postId))
    )
   .subscribe(() => console.log('upvoted!'))

Upvotes: 3

Collin
Collin

Reputation: 444

(A more simple answer)

Say a user clicks a button that triggers a request (example):

Throttle time = can limit the number of clicks so only 1 goes through every second (prevents button spamming)

Debounce time = can add a delay before each request goes through (you press the button then nothing happens for 1 seconds, then your request goes through)

1 second was just an example. You can enter whatever you'd in the debounceTime() or throttleTime() - in ms

Upvotes: 12

Harijs Deksnis
Harijs Deksnis

Reputation: 1496

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.

Upvotes: 70

Related Questions