Learn RxJS
Search…
bufferTime

signature: bufferTime(bufferTimeSpan: number, bufferCreationInterval: number, scheduler: Scheduler): Observable

Collect emitted values until provided time has passed, emit as array.

Examples

Example 1: Buffer for 2 seconds
1
// RxJS v6+
2
import { interval } from 'rxjs';
3
import { bufferTime } from 'rxjs/operators';
4
5
//Create an observable that emits a value every 500ms
6
const source = interval(500);
7
//After 2 seconds have passed, emit buffered values as an array
8
const example = source.pipe(bufferTime(2000));
9
//Print values to console
10
//ex. output [0,1,2]...[3,4,5,6]
11
const subscribe = example.subscribe(val =>
12
console.log('Buffered with Time:', val)
13
);
Copied!
Example 2: Multiple active buffers
1
// RxJS v6+
2
import { interval } from 'rxjs';
3
import { bufferTime } from 'rxjs/operators';
4
5
//Create an observable that emits a value every 500ms
6
const source = interval(500);
7
/*
8
bufferTime also takes second argument, when to start the next buffer (time in ms)
9
for instance, if we have a bufferTime of 2 seconds but second argument (bufferCreationInterval) of 1 second:
10
ex. output: [0,1,2]...[1,2,3,4,5]...[3,4,5,6,7]
11
*/
12
const example = source.pipe(bufferTime(2000, 1000));
13
//Print values to console
14
const subscribe = example.subscribe(val =>
15
console.log('Start Buffer Every 1s:', val)
16
);
Copied!

Additional Resources