问题描述
我想了解throttleTime
与debounceTime
以及何时使用哪个?
I'm trying to understand throttleTime
vs debounceTime
and which one is to be used when?
我有一个upvote按钮,该按钮向后端发出一个API请求(对票数进行计数).用户可以多次提交按钮,但我想限制每秒可以按下按钮的次数.
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.
我知道油门时间和debounceTime运算符可以做到这一点,但是我应该选择哪个更好呢?
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));
推荐答案
在您的情况下,我认为throttleTime
的效果要好一些,因为您希望在用户单击按钮后立即发出api请求.
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.
throttleTime
和debounceTime
都忽略了同时发生的事件,但是throttleTime
立即发出,而debounceTime
等待其他延迟.
Both throttleTime
and debounceTime
ignore the events which come in the meantime, but throttleTime
emits right away, whiledebounceTime
waits for additional delay.
您可以在 https://rxmarbles.com 上直观地看到这一点.
You can visually see that very well at https://rxmarbles.com
此外, RxJS中的throttleTime与debounceTime 文章提供了很好地概述了这两个运算符.
What is more, throttleTime vs debounceTime in RxJS article provides a good overview of both operators.
这篇关于rxjs中的油门时间与debounceTime之间的区别以及何时选择哪个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!