85693702007cec38624d4de47dd5a4f7a0dbae6a9b2915d40c5b8212bcb63a3bdef76cbf4da5e945b2383dd79cdd2b486f83a34473742e3a7e5547b9590538 2.4 KB

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