a683b654a2d18d28bae53de4f5630fc8f0aac65cb447ff62313d0fd3638d9821d684ddf646818de4cba22b1c202befada186bd9afba5c6c89133bcf6839d55 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { Observable } from '../Observable';
  2. import { asyncScheduler } from '../scheduler/async';
  3. import { SchedulerLike } from '../types';
  4. import { timer } from './timer';
  5. /**
  6. * Creates an Observable that emits sequential numbers every specified
  7. * interval of time, on a specified {@link SchedulerLike}.
  8. *
  9. * <span class="informal">Emits incremental numbers periodically in time.</span>
  10. *
  11. * ![](interval.png)
  12. *
  13. * `interval` returns an Observable that emits an infinite sequence of
  14. * ascending integers, with a constant interval of time of your choosing
  15. * between those emissions. The first emission is not sent immediately, but
  16. * only after the first period has passed. By default, this operator uses the
  17. * `async` {@link SchedulerLike} to provide a notion of time, but you may pass any
  18. * {@link SchedulerLike} to it.
  19. *
  20. * ## Example
  21. *
  22. * Emits ascending numbers, one every second (1000ms) up to the number 3
  23. *
  24. * ```ts
  25. * import { interval, take } from 'rxjs';
  26. *
  27. * const numbers = interval(1000);
  28. *
  29. * const takeFourNumbers = numbers.pipe(take(4));
  30. *
  31. * takeFourNumbers.subscribe(x => console.log('Next: ', x));
  32. *
  33. * // Logs:
  34. * // Next: 0
  35. * // Next: 1
  36. * // Next: 2
  37. * // Next: 3
  38. * ```
  39. *
  40. * @see {@link timer}
  41. * @see {@link delay}
  42. *
  43. * @param period The interval size in milliseconds (by default) or the time unit determined
  44. * by the scheduler's clock.
  45. * @param scheduler The {@link SchedulerLike} to use for scheduling the emission of values,
  46. * and providing a notion of "time".
  47. * @return An Observable that emits a sequential number each time interval.
  48. */
  49. export function interval(period = 0, scheduler: SchedulerLike = asyncScheduler): Observable<number> {
  50. if (period < 0) {
  51. // We cannot schedule an interval in the past.
  52. period = 0;
  53. }
  54. return timer(period, period, scheduler);
  55. }