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

会有一股神秘感。 提交于 2019-12-22 08:51:35

问题


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 should I choose better?

const upvoteClicks = fromEvent(this.el.nativeElement, 'click')
 .pipe(debounceTime(500))
 .subscribe(() => this.myService.postUpvote(this.postId));


回答1:


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

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



来源:https://stackoverflow.com/questions/56460436/what-is-the-difference-between-throttletime-vs-debouncetime-in-rxjs-and-when-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!