我想了解 throttleTime
与 debounceTime
以及何时使用哪个?
我有一个投票按钮,可以向后端发出 API 请求(计算选票)。用户可以多次提交按钮,但我想限制每秒可以按下按钮的次数。
我知道 throttleTime
和 debounceTime
运算符可以做到这一点,但我应该选择哪一个?
const upvoteClicks = fromEvent(this.el.nativeElement, 'click')
.pipe(debounceTime(500))
.subscribe(() => this.myService.postUpvote(this.postId));
最佳答案
我认为在你的情况下 throttleTime
工作得更好一点,因为你想在用户点击按钮时立即发出 api 请求。
throttleTime
和 debounceTime
都会忽略同时发生的事件,但是 throttleTime
会立即发出,而
debounceTime
等待额外的延迟。
您可以在 https://rxmarbles.com 上直观地看到这一点
此外,throttleTime vs debounceTime in RxJS这篇文章很好地概述了这两个运算符。
关于rxjs - RxJS 中的 throttleTime 与 debounceTime 之间有什么区别以及何时选择哪个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56460436/