Learn RxJS
Search…
Time based operators comparison
RxJS offers a rich selection of time based operators but this diversity can come at cost when choosing the right operator for a task at hand. Below is a visual comparison of popular time based operators.
Compared operators:
1
/*
2
interval ^0-------1-------2-------3-------4-------5-------6-------7-------8-------9------|
3
auditTime ^------------------------3-------------------------------7----------------------|
4
bufferTime ^----------------[0,1]-------------------[2,3,4]-----------------[5,6,7]-[8,9]--|
5
debounceTime ^------------------------------------------------------------------------9------|
6
sampleTime ^----------------1-----------------------4-----------------------7--------------|
7
throttleTime ^0-------------------------------4-------------------------------8--------------|
8
*/
9
10
// RxJS v6+
11
import { interval, merge } from 'rxjs';
12
import { auditTime, bufferTime, debounceTime, sampleTime, throttleTime, tap, take } from 'rxjs/operators';
13
14
const takeValue = 10;
15
const intrvl = 1000;
16
const time = 3000;
17
18
const intervaled = (operator, operatorName) =>
19
interval(intrvl)
20
.pipe(
21
take(takeValue),
22
operator,
23
tap(x => console.log(`${operatorName}:${x}`))
24
);
25
26
merge(
27
interval(intrvl).pipe(take(takeValue), tap(v => console.log(`i: ${v}`))),
28
intervaled(auditTime(time), "auditTime"),
29
intervaled(bufferTime(time), "bufferTime"),
30
intervaled(debounceTime(time), "debounceTime"),
31
intervaled(sampleTime(time), "sampleTime"),
32
intervaled(throttleTime(time), "throttleTime")
33
).subscribe();
34
35
// output
36
/*
37
i: 0
38
throttleTime:0
39
i: 1
40
i: 2
41
bufferTime:0,1
42
sampleTime:1
43
i: 3
44
auditTime:3
45
i: 4
46
throttleTime:4
47
i: 5
48
bufferTime:2,3,4
49
sampleTime:4
50
i: 6
51
i: 7
52
auditTime:7
53
i: 8
54
bufferTime:5,6,7
55
sampleTime:7
56
throttleTime:8
57
i: 9
58
bufferTime:8,9
59
debounceTime:9
60
61
*/
Copied!
Last modified 1yr ago
Copy link