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:
- when new value arrives schedule a new interval
- emit the value to the observer
- if a new value comes before the interval ends, ignore it
The following diagram demonstrates this sequence of steps:
For the configuration {leading: true, trailing: true}
the operator works in the following way:
- when new value arrives schedule a new interval
- emit the value to the observer
- if a new value comes before the interval ends, keep it and override the existing one
- once the interval ends, emit the value to the observer
The following diagram demonstrates this sequence of steps:
For the configuration {leading: false, trailing: true}
the operator works in the following way:
- when new value arrives schedule a new interval
- keep the value
- if a new value comes before the interval ends, keep it and override the existing one
- once the interval ends, emit the value to the observer
The following diagram demonstrates this sequence of steps:
By default the operator uses setInterval
through AsyncScheduler under the hood for scheduling.
UsageLink to this section
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:
<>Copyconst 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));