59d3b1ed73e287b4151e818a6edff8f58216ffc19b998563a719be4d61e01223f85aadc57bbe871922fc28fef476b41526ed657d2a6cb3d48706ad3028df4c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { asyncScheduler } from '../scheduler/async';
  2. import { MonoTypeOperatorFunction, SchedulerLike } from '../types';
  3. import { delayWhen } from './delayWhen';
  4. import { timer } from '../observable/timer';
  5. /**
  6. * Delays the emission of items from the source Observable by a given timeout or
  7. * until a given Date.
  8. *
  9. * <span class="informal">Time shifts each item by some specified amount of
  10. * milliseconds.</span>
  11. *
  12. * ![](delay.svg)
  13. *
  14. * If the delay argument is a Number, this operator time shifts the source
  15. * Observable by that amount of time expressed in milliseconds. The relative
  16. * time intervals between the values are preserved.
  17. *
  18. * If the delay argument is a Date, this operator time shifts the start of the
  19. * Observable execution until the given date occurs.
  20. *
  21. * ## Examples
  22. *
  23. * Delay each click by one second
  24. *
  25. * ```ts
  26. * import { fromEvent, delay } from 'rxjs';
  27. *
  28. * const clicks = fromEvent(document, 'click');
  29. * const delayedClicks = clicks.pipe(delay(1000)); // each click emitted after 1 second
  30. * delayedClicks.subscribe(x => console.log(x));
  31. * ```
  32. *
  33. * Delay all clicks until a future date happens
  34. *
  35. * ```ts
  36. * import { fromEvent, delay } from 'rxjs';
  37. *
  38. * const clicks = fromEvent(document, 'click');
  39. * const date = new Date('March 15, 2050 12:00:00'); // in the future
  40. * const delayedClicks = clicks.pipe(delay(date)); // click emitted only after that date
  41. * delayedClicks.subscribe(x => console.log(x));
  42. * ```
  43. *
  44. * @see {@link delayWhen}
  45. * @see {@link throttle}
  46. * @see {@link throttleTime}
  47. * @see {@link debounce}
  48. * @see {@link debounceTime}
  49. * @see {@link sample}
  50. * @see {@link sampleTime}
  51. * @see {@link audit}
  52. * @see {@link auditTime}
  53. *
  54. * @param due The delay duration in milliseconds (a `number`) or a `Date` until
  55. * which the emission of the source items is delayed.
  56. * @param scheduler The {@link SchedulerLike} to use for managing the timers
  57. * that handle the time-shift for each item.
  58. * @return A function that returns an Observable that delays the emissions of
  59. * the source Observable by the specified timeout or Date.
  60. */
  61. export function delay<T>(due: number | Date, scheduler: SchedulerLike = asyncScheduler): MonoTypeOperatorFunction<T> {
  62. const duration = timer(due, scheduler);
  63. return delayWhen(() => duration);
  64. }