Emits the most recently emitted value from the source Observable within periodic time intervals.
sampleTime periodically looks at the source Observable and emits whichever value it has most recently emitted since the previous sampling, unless the source has not emitted anything since the previous sampling.
MonoTypeOperatorFunction<T> - A function that returns an Observable that emits the results of sampling the values emitted by the source Observable at the specified time interval.
import { fromEvent, sampleTime } from 'rxjs';const clicks = fromEvent(document, 'click');const result = clicks.pipe(sampleTime(1000));result.subscribe(x => console.log(x));// Emits at most one click per second
import { interval, sampleTime, auditTime, throttleTime, take } from 'rxjs';const fast$ = interval(100).pipe(take(50));// sampleTime: Samples every period (last value)fast$.pipe(sampleTime(500)).subscribe(x => console.log('sampleTime:', x));// Output: ~4, ~9, ~14, ~19, ...// auditTime: Emits last value after each periodfast$.pipe(auditTime(500)).subscribe(x => console.log('auditTime:', x));// Output: ~4, ~9, ~14, ~19, ...// throttleTime: Emits first value of each periodfast$.pipe(throttleTime(500)).subscribe(x => console.log('throttleTime:', x));// Output: 0, ~5, ~10, ~15, ...
For most use cases, sampleTime and auditTime behave similarly. The key difference is that auditTime waits for the silence period after each emission, while sampleTime samples at fixed intervals regardless of emissions.
import { fromEvent, sampleTime } from 'rxjs';// WITHOUT sampleTime: Expensive operation on every eventfromEvent(window, 'scroll').subscribe(() => { updateComplexVisualization(); // Called hundreds of times per second!});// WITH sampleTime: Controlled update ratefromEvent(window, 'scroll').pipe( sampleTime(100) // Maximum 10 updates per second).subscribe(() => { updateComplexVisualization(); // Much better performance!});