| 1 |
import { asyncScheduler } from '../scheduler/async'; |
| 2 |
import { throttle, ThrottleConfig } from './throttle'; |
| 3 |
import { MonoTypeOperatorFunction, SchedulerLike } from '../types'; |
| 4 |
import { timer } from '../observable/timer'; |
| 5 |
|
| 6 |
/** |
| 7 |
* Emits a value from the source Observable, then ignores subsequent source |
| 8 |
* values for `duration` milliseconds, then repeats this process. |
| 9 |
* |
| 10 |
* <span class="informal">Lets a value pass, then ignores source values for the |
| 11 |
* next `duration` milliseconds.</span> |
| 12 |
* |
| 13 |
*  |
| 14 |
* |
| 15 |
* `throttleTime` emits the source Observable values on the output Observable |
| 16 |
* when its internal timer is disabled, and ignores source values when the timer |
| 17 |
* is enabled. Initially, the timer is disabled. As soon as the first source |
| 18 |
* value arrives, it is forwarded to the output Observable, and then the timer |
| 19 |
* is enabled. After `duration` milliseconds (or the time unit determined |
| 20 |
* internally by the optional `scheduler`) has passed, the timer is disabled, |
| 21 |
* and this process repeats for the next source value. Optionally takes a |
| 22 |
* {@link SchedulerLike} for managing timers. |
| 23 |
* |
| 24 |
* ## Examples |
| 25 |
* |
| 26 |
* ### Limit click rate |
| 27 |
* |
| 28 |
* Emit clicks at a rate of at most one click per second |
| 29 |
* |
| 30 |
* ```ts |
| 31 |
* import { fromEvent, throttleTime } from 'rxjs'; |
| 32 |
* |
| 33 |
* const clicks = fromEvent(document, 'click'); |
| 34 |
* const result = clicks.pipe(throttleTime(1000)); |
| 35 |
* |
| 36 |
* result.subscribe(x => console.log(x)); |
| 37 |
* ``` |
| 38 |
* |
| 39 |
* @see {@link auditTime} |
| 40 |
* @see {@link debounceTime} |
| 41 |
* @see {@link delay} |
| 42 |
* @see {@link sampleTime} |
| 43 |
* @see {@link throttle} |
| 44 |
* |
| 45 |
* @param duration Time to wait before emitting another value after |
| 46 |
* emitting the last value, measured in milliseconds or the time unit determined |
| 47 |
* internally by the optional `scheduler`. |
| 48 |
* @param scheduler The {@link SchedulerLike} to use for |
| 49 |
* managing the timers that handle the throttling. Defaults to {@link asyncScheduler}. |
| 50 |
* @param config A configuration object to define `leading` and |
| 51 |
* `trailing` behavior. Defaults to `{ leading: true, trailing: false }`. |
| 52 |
* @return A function that returns an Observable that performs the throttle |
| 53 |
* operation to limit the rate of emissions from the source. |
| 54 |
*/ |
| 55 |
export function throttleTime<T>( |
| 56 |
duration: number, |
| 57 |
scheduler: SchedulerLike = asyncScheduler, |
| 58 |
config?: ThrottleConfig |
| 59 |
): MonoTypeOperatorFunction<T> { |
| 60 |
const duration$ = timer(duration, scheduler); |
| 61 |
return throttle(() => duration$, config); |
| 62 |
} |