Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

observable - 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));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...