-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
timer-impl.js
204 lines (187 loc) · 5.29 KB
/
timer-impl.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
/**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {getMode} from '../mode';
import {
registerServiceBuilder,
registerServiceBuilderInEmbedWin,
} from '../service';
import {reportError} from '../error';
import {user} from '../log';
const TAG = 'timer';
let timersForTesting;
/**
* Helper with all things Timer.
*/
export class Timer {
/**
* @param {!Window} win
*/
constructor(win) {
/** @const {!Window} */
this.win = win;
/** @private @const {!Promise} */
this.resolved_ = this.win.Promise.resolve();
this.taskCount_ = 0;
this.canceled_ = {};
/** @const {number} */
this.startTime_ = Date.now();
}
/**
* Returns time since start in milliseconds.
* @return {number}
*/
timeSinceStart() {
return Date.now() - this.startTime_;
}
/**
* Runs the provided callback after the specified delay. This uses a micro
* task for 0 or no specified time. This means that the delay will actually
* be close to 0 and this will NOT yield to the event queue.
*
* Returns the timer ID that can be used to cancel the timer (cancel method).
* @param {function()} callback
* @param {number=} opt_delay
* @return {number|string}
*/
delay(callback, opt_delay) {
if (!opt_delay) {
// For a delay of zero, schedule a promise based micro task since
// they are predictably fast.
const id = 'p' + this.taskCount_++;
this.resolved_
.then(() => {
if (this.canceled_[id]) {
delete this.canceled_[id];
return;
}
callback();
})
.catch(reportError);
return id;
}
const wrapped = () => {
try {
callback();
} catch (e) {
reportError(e);
throw e;
}
};
const index = this.win.setTimeout(wrapped, opt_delay);
if (getMode().test) {
if (!timersForTesting) {
timersForTesting = [];
}
timersForTesting.push(index);
}
return index;
}
/**
* Cancels the previously scheduled callback.
* @param {number|string|null} timeoutId
*/
cancel(timeoutId) {
if (typeof timeoutId == 'string') {
this.canceled_[timeoutId] = true;
return;
}
this.win.clearTimeout(timeoutId);
}
/**
* Returns a promise that will resolve after the delay. Optionally, the
* resolved value can be provided as opt_result argument.
* @param {number=} opt_delay
* @return {!Promise}
*/
promise(opt_delay) {
return new this.win.Promise((resolve) => {
// Avoid wrapping in closure if no specific result is produced.
const timerKey = this.delay(resolve, opt_delay);
if (timerKey == -1) {
throw new Error('Failed to schedule timer.');
}
});
}
/**
* Returns a promise that will fail after the specified delay. Optionally,
* this method can take opt_racePromise parameter. In this case, the
* resulting promise will either fail when the specified delay expires or
* will resolve based on the opt_racePromise, whichever happens first.
* @param {number} delay
* @param {?Promise<RESULT>|undefined} opt_racePromise
* @param {string=} opt_message
* @return {!Promise<RESULT>}
* @template RESULT
*/
timeoutPromise(delay, opt_racePromise, opt_message) {
let timerKey;
const delayPromise = new this.win.Promise((_resolve, reject) => {
timerKey = this.delay(() => {
reject(user().createError(opt_message || 'timeout'));
}, delay);
if (timerKey == -1) {
throw new Error('Failed to schedule timer.');
}
});
if (!opt_racePromise) {
return delayPromise;
}
const cancel = () => {
this.cancel(timerKey);
};
opt_racePromise.then(cancel, cancel);
return this.win.Promise.race([delayPromise, opt_racePromise]);
}
/**
* Returns a promise that resolves after `predicate` returns true.
* Polls with interval `delay`
* @param {number} delay
* @param {function():boolean} predicate
* @return {!Promise}
*/
poll(delay, predicate) {
return new this.win.Promise((resolve) => {
const interval = this.win.setInterval(() => {
if (predicate()) {
this.win.clearInterval(interval);
resolve();
}
}, delay);
});
}
}
/**
* @param {!Window} window
*/
export function installTimerService(window) {
registerServiceBuilder(window, TAG, Timer);
}
/**
* @param {!Window} embedWin
*/
export function installTimerInEmbedWindow(embedWin) {
registerServiceBuilderInEmbedWin(embedWin, TAG, Timer);
}
/**
* Cancels all timers scheduled during the current test
*/
export function cancelTimersForTesting() {
if (!timersForTesting) {
return;
}
timersForTesting.forEach(clearTimeout);
timersForTesting = null;
}