24 Jul 2024
2 min

sampleTime – RxJS Reference

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, while throttleTime only schedules a new interval when new value comes from the source observable. This might have big effect on performance and hence auditTime 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, while sampleTime discards it.

The operator works in the following way:

  1. schedule a new interval
  2. when a new value arrives keep it and override the existing one
  3. once the interval ends, emit the value to the observer
  4. schedule a new interval
  5. 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.

Usage

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:

const 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));

Playground

Additional resources

See also

Frequently asked questions

What is the difference between sampleTime and throttleTime in RxJS?

sampleTime behaves like throttleTime configured with {leading: false, trailing: true}, but it keeps scheduling new intervals whether or not the source emits. throttleTime only starts a new interval when a new value arrives. Also, if the source completes before the interval ends, sampleTime discards the pending value, while throttleTime still sends it to the observer.

How do I limit how often values are emitted from an observable in RxJS?

Use the sampleTime(ms) operator in a pipe(), passing the interval in milliseconds. It keeps the latest value received during each interval and emits it once the interval ends, so the output is regular but never faster than the configured rate. For example, sampleTime(500) emits at most one value every 500 ms. It is mostly used for high-frequency events like scroll, resize, mouse movement, and keypress.

Why does sampleTime discard the last value when the source completes?

sampleTime discards the current value if the source observable completes before the interval ends, because it only emits when the interval finishes. This differs from throttleTime, which still forwards that value. If you need the final value delivered on completion, consider a different operator, such as auditTime, which is recommended as a preferred rate-limiting operator in the article.

When should I use auditTime instead of sampleTime in RxJS?

Use auditTime when you want rate limiting that only schedules work in response to source emissions. sampleTime keeps scheduling intervals even when the source is silent, which can affect performance. The article recommends auditTime as the preferred operator for rate-limiting. sampleTime remains suitable when you need regularly spaced emissions at a fixed interval, for example sampling DOM events every 500 ms.

Does sampleTime use setInterval under the hood in RxJS?

Yes, by default sampleTime schedules its intervals through the AsyncScheduler, which uses setInterval internally. Because it schedules intervals regardless of source activity, it keeps ticking even when no new values arrive. You can customize timing by passing a scheduler as the second argument, for example sampleTime(500, asapScheduler), though the default AsyncScheduler is what the operator uses out of the box.

Share this post

Sign up for our newsletter

Stay up-to-date with the trends and be a part of a thriving community.