Debian Codegraph @

node/rxjs/src/internal/observable/timer.ts

raw
1 import { Observable } from '../Observable';
2 import { SchedulerLike } from '../types';
3 import { async as asyncScheduler } from '../scheduler/async';
4 import { isScheduler } from '../util/isScheduler';
5 import { isValidDate } from '../util/isDate';
6
7 /**
8 * Creates an observable that will wait for a specified time period, or exact date, before
9 * emitting the number 0.
10 *
11 * <span class="informal">Used to emit a notification after a delay.</span>
12 *
13 * This observable is useful for creating delays in code, or racing against other values
14 * for ad-hoc timeouts.
15 *
16 * The `delay` is specified by default in milliseconds, however providing a custom scheduler could
17 * create a different behavior.
18 *
19 * ## Examples
20 *
21 * Wait 3 seconds and start another observable
22 *
23 * You might want to use `timer` to delay subscription to an
24 * observable by a set amount of time. Here we use a timer with
25 * {@link concatMapTo} or {@link concatMap} in order to wait
26 * a few seconds and start a subscription to a source.
27 *
28 * ```ts
29 * import { of, timer, concatMap } from 'rxjs';
30 *
31 * // This could be any observable
32 * const source = of(1, 2, 3);
33 *
34 * timer(3000)
35 * .pipe(concatMap(() => source))
36 * .subscribe(console.log);
37 * ```
38 *
39 * Take all values until the start of the next minute
40 *
41 * Using a `Date` as the trigger for the first emission, you can
42 * do things like wait until midnight to fire an event, or in this case,
43 * wait until a new minute starts (chosen so the example wouldn't take
44 * too long to run) in order to stop watching a stream. Leveraging
45 * {@link takeUntil}.
46 *
47 * ```ts
48 * import { interval, takeUntil, timer } from 'rxjs';
49 *
50 * // Build a Date object that marks the
51 * // next minute.
52 * const currentDate = new Date();
53 * const startOfNextMinute = new Date(
54 * currentDate.getFullYear(),
55 * currentDate.getMonth(),
56 * currentDate.getDate(),
57 * currentDate.getHours(),
58 * currentDate.getMinutes() + 1
59 * );
60 *
61 * // This could be any observable stream
62 * const source = interval(1000);
63 *
64 * const result = source.pipe(
65 * takeUntil(timer(startOfNextMinute))
66 * );
67 *
68 * result.subscribe(console.log);
69 * ```
70 *
71 * ### Known Limitations
72 *
73 * - The {@link asyncScheduler} uses `setTimeout` which has limitations for how far in the future it can be scheduled.
74 *
75 * - If a `scheduler` is provided that returns a timestamp other than an epoch from `now()`, and
76 * a `Date` object is passed to the `dueTime` argument, the calculation for when the first emission
77 * should occur will be incorrect. In this case, it would be best to do your own calculations
78 * ahead of time, and pass a `number` in as the `dueTime`.
79 *
80 * @param due If a `number`, the amount of time in milliseconds to wait before emitting.
81 * If a `Date`, the exact time at which to emit.
82 * @param scheduler The scheduler to use to schedule the delay. Defaults to {@link asyncScheduler}.
83 */
84 export function timer(due: number | Date, scheduler?: SchedulerLike): Observable<0>;
85
86 /**
87 * Creates an observable that starts an interval after a specified delay, emitting incrementing numbers -- starting at `0` --
88 * on each interval after words.
89 *
90 * The `delay` and `intervalDuration` are specified by default in milliseconds, however providing a custom scheduler could
91 * create a different behavior.
92 *
93 * ## Example
94 *
95 * ### Start an interval that starts right away
96 *
97 * Since {@link interval} waits for the passed delay before starting,
98 * sometimes that's not ideal. You may want to start an interval immediately.
99 * `timer` works well for this. Here we have both side-by-side so you can
100 * see them in comparison.
101 *
102 * Note that this observable will never complete.
103 *
104 * ```ts
105 * import { timer, interval } from 'rxjs';
106 *
107 * timer(0, 1000).subscribe(n => console.log('timer', n));
108 * interval(1000).subscribe(n => console.log('interval', n));
109 * ```
110 *
111 * ### Known Limitations
112 *
113 * - The {@link asyncScheduler} uses `setTimeout` which has limitations for how far in the future it can be scheduled.
114 *
115 * - If a `scheduler` is provided that returns a timestamp other than an epoch from `now()`, and
116 * a `Date` object is passed to the `dueTime` argument, the calculation for when the first emission
117 * should occur will be incorrect. In this case, it would be best to do your own calculations
118 * ahead of time, and pass a `number` in as the `startDue`.
119 * @param startDue If a `number`, is the time to wait before starting the interval.
120 * If a `Date`, is the exact time at which to start the interval.
121 * @param intervalDuration The delay between each value emitted in the interval. Passing a
122 * negative number here will result in immediate completion after the first value is emitted, as though
123 * no `intervalDuration` was passed at all.
124 * @param scheduler The scheduler to use to schedule the delay. Defaults to {@link asyncScheduler}.
125 */
126 export function timer(startDue: number | Date, intervalDuration: number, scheduler?: SchedulerLike): Observable<number>;
127
128 /**
129 * @deprecated The signature allowing `undefined` to be passed for `intervalDuration` will be removed in v8. Use the `timer(dueTime, scheduler?)` signature instead.
130 */
131 export function timer(dueTime: number | Date, unused: undefined, scheduler?: SchedulerLike): Observable<0>;
132
133 export function timer(
134 dueTime: number | Date = 0,
135 intervalOrScheduler?: number | SchedulerLike,
136 scheduler: SchedulerLike = asyncScheduler
137 ): Observable<number> {
138 // Since negative intervalDuration is treated as though no
139 // interval was specified at all, we start with a negative number.
140 let intervalDuration = -1;
141
142 if (intervalOrScheduler != null) {
143 // If we have a second argument, and it's a scheduler,
144 // override the scheduler we had defaulted. Otherwise,
145 // it must be an interval.
146 if (isScheduler(intervalOrScheduler)) {
147 scheduler = intervalOrScheduler;
148 } else {
149 // Note that this *could* be negative, in which case
150 // it's like not passing an intervalDuration at all.
151 intervalDuration = intervalOrScheduler;
152 }
153 }
154
155 return new Observable((subscriber) => {
156 // If a valid date is passed, calculate how long to wait before
157 // executing the first value... otherwise, if it's a number just schedule
158 // that many milliseconds (or scheduler-specified unit size) in the future.
159 let due = isValidDate(dueTime) ? +dueTime - scheduler!.now() : dueTime;
160
161 if (due < 0) {
162 // Ensure we don't schedule in the future.
163 due = 0;
164 }
165
166 // The incrementing value we emit.
167 let n = 0;
168
169 // Start the timer.
170 return scheduler.schedule(function () {
171 if (!subscriber.closed) {
172 // Emit the next value and increment.
173 subscriber.next(n++);
174
175 if (0 <= intervalDuration) {
176 // If we have a interval after the initial timer,
177 // reschedule with the period.
178 this.schedule(undefined, intervalDuration);
179 } else {
180 // We didn't have an interval. So just complete.
181 subscriber.complete();
182 }
183 }
184 }, due);
185 });
186 }