本文介绍了RxJS 中的 ThrottleTime 与 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.

我知道 throttleTimedebounceTime 操作符可以做到这一点,但我应该选择哪一个?

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

推荐答案

我认为在你的情况下 throttleTime 工作得更好一点,因为你想在用户点击按钮.

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.

您可以在

此外,RxJS 中的throttleTime vs debounceTime 文章提供对这两个运算符的一个很好的概述.

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

这篇关于RxJS 中的 ThrottleTime 与 debounceTime 之间有什么区别以及何时选择哪个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 06:09