本文介绍了rxjs中的油门时间与debounceTime之间的区别以及何时选择哪个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解throttleTimedebounceTime以及何时使用哪个?

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.

throttleTimedebounceTime都忽略了同时发生的事件,但是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之间的区别以及何时选择哪个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 15:49