24 Jul 2024
5 min

throttleTime – RxJS Reference

throttleTime

throttleTime 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, throttleTime guarantees the values will be emitted regurarly, but not more often than the configured interval.

This operator takes an optional configuration parameter that can change the behavior of the operator: {leading: boolean, trailing: boolean}. The default settings are {leading: true, trailing: false}.

For the default configuration {leading: true, trailing: false} the operator works in the following way:

  1. when new value arrives schedule a new interval
  2. emit the value to the observer
  3. if a new value comes before the interval ends, ignore it

For the configuration {leading: true, trailing: true} the operator works in the following way:

  1. when new value arrives schedule a new interval
  2. emit the value to the observer
  3. if a new value comes before the interval ends, keep it and override the existing one
  4. once the interval ends, emit the value to the observer

For the configuration {leading: false, trailing: true} the operator works in the following way:

  1. when new value arrives schedule a new interval
  2. keep the value
  3. if a new value comes before the interval ends, keep it and override the existing one
  4. once the interval ends, emit the value to the observer

By default the operator uses setInterval through AsyncScheduler under the hood for scheduling.

Usage

This operator 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 throttleTime on an input:

const inputElement = document.createElement('input');
document.body.appendChild(inputElement);

fromEvent(inputElement, 'input')
   .pipe(
       throttleTime(500),
       map((event: any) => event.target.value)
   ).subscribe(val => console.log(val));

Playground

Leading – true, Trailing – false

Leading – true, Trailing – true

Leading – false, Trailing – true

Additional resources

See also

Share this post

Sign up for our newsletter

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