sampleTime
sampleTime
delays the values emitted by a source for the given due time. Similarly to debounceTime, this operator can be used to control the rate with which the values are emitted to an observer. Unlike debounceTime
though, sampleTime
guarantees the values will be emitted regurarly, but not more often than the configured interval.
sampleTime
is similar to throttleTime with the configuration {leading: false, trailing: true}
. There are two significant differences:
sampleTime
keeps scheduling new intervals regardless if If the source observable emits new values or not, whilethrottleTime
only schedules a new interval when new value comes from the source observable. This might have big effect on performance and henceauditTime
is a preferred operator to be used for rate-limiting.- If the source observable completes before the interval ends,
throttleTime
still sends the value to an observer, whilesampleTime
discards it.
The operator works in the following way:
- schedule a new interval
- when a new value arrives keep it and override the existing one
- once the interval ends, emit the value to the observer
- schedule a new interval
- if the source observable completes before the interval ends, discard the current value
By default the operator uses setInterval
through AsyncScheduler under the hood for scheduling.
The following diagram demonstrates this sequence of steps:
UsageLink to this section
When you are interested in ignoring values from a source observable for a given amount of time, you can use sampleTime
. It is mostly used for events that can be triggered tens or even hundreds of times per second. The most common examples are DOM events such as scrolling, resizing, mouse movements, and keypress.
For example, if you attach a scroll handler to an element, and scroll that element down to say 5000px, you’re likely to see 100+ events being fired. If your event handler performs multiple tasks (like heavy calculations and other DOM manipulation), you may see performance issues (jank). Reducing the number of times this handler is executed without disrupting user experience will have a significant effect on performance.
In addition, you should consider wrapping any interaction that triggers excessive calculations or API calls with a throttle.
Here’s an example of using sampleTime
on an input:
<>Copyconst inputElement = document.createElement('input'); document.body.appendChild(inputElement); fromEvent(inputElement, 'input') .pipe( sampleTime(500), map((event: any) => event.target.value) ).subscribe(val => console.log(val));