rxjs - RxJS 中的 throttleTime 与 debounceTime 之间有什么区别以及何时选择哪个?

标签 rxjs observable rxjs-pipeable-operators

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

我有一个投票按钮,可以向后端发出 API 请求(计算选票)。用户可以多次提交按钮,但我想限制每秒可以按下按钮的次数。

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

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

最佳答案

我认为在你的情况下 throttleTime 工作得更好一点,因为你想在用户点击按钮时立即发出 api 请求。

throttleTimedebounceTime 都会忽略同时发生的事件,但是 throttleTime 会立即发出,而 debounceTime 等待额外的延迟。

您可以在 https://rxmarbles.com 上直观地看到这一点 enter image description here

enter image description here

此外,throttleTime vs debounceTime in RxJS这篇文章很好地概述了这两个运算符。

关于rxjs - RxJS 中的 throttleTime 与 debounceTime 之间有什么区别以及何时选择哪个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56460436/

相关文章:

angular - RXJS Observable 移除管道操作符

javascript - 将 Observable 用于 AWS cognito 回调

文档中的 Angular FireStore 集合

javascript - 如何基于另一个 Observable 重置 RXJS 扫描操作符

Angular 6 过滤异步管道结果

javascript - 为什么当我的变量从可观察到的值每秒接收到一个新值时,ngModal不会更新输入值

javascript - 使用 JavaScript 映射和缩减 JSON 对象

jquery - KendoUI 可观察对象 : Set multiple attributes

angular - 如何停止 IntervalObservable

angular - RxJs 在返回的数组上循环