throttleTime
优质
小牛编辑
137浏览
2023-12-01
throttleTime
函数签名: throttleTime(duration: number, scheduler: Scheduler): Observable
当指定的持续时间经过后发出最新值。
示例
示例 1: 每5秒接收最新值
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+
import { interval } from 'rxjs';
import { throttleTime } from 'rxjs/operators';
// 每1秒发出值
const source = interval(1000);
/*
节流5秒
节流结束前发出的最后一个值将从源 observable 中发出
*/
const example = source.pipe(throttleTime(5000));
// 输出: 0...6...12
const subscribe = example.subscribe(val => console.log(val));
示例 2: 对合并的 observable 节流
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+
import { interval, merge } from 'rxjs';
import { throttleTime, ignoreElements } from 'rxjs/operators';
const source = merge(
// 每0.75秒发出值
interval(750),
// 每1秒发出值
interval(1000)
);
// 在发出值的中间进行节流
const example = source.pipe(throttleTime(1200));
// 输出: 0...1...4...4...8...7
const subscribe = example.subscribe(val => console.log(val));
其他资源
- throttleTime :newspaper: - 官方文档
- 过滤操作符: throttle 和 throttleTime :video_camera: :dollar: - André Staltz
源码: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/throttleTime.ts