-
-
Notifications
You must be signed in to change notification settings - Fork 773
/
timer.js
37 lines (28 loc) · 863 Bytes
/
timer.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
// @flow
// Animation frame based implementation of setTimeout.
// Inspired by Joe Lambert, https://gist.github.com/joelambert/1002116#file-requesttimeout-js
const hasNativePerformanceNow =
typeof performance === 'object' && typeof performance.now === 'function';
const now = hasNativePerformanceNow
? () => performance.now()
: () => Date.now();
export type TimeoutID = {|
id: AnimationFrameID,
|};
export function cancelTimeout(timeoutID: TimeoutID) {
cancelAnimationFrame(timeoutID.id);
}
export function requestTimeout(callback: Function, delay: number): TimeoutID {
const start = now();
function tick() {
if (now() - start >= delay) {
callback.call(null);
} else {
timeoutID.id = requestAnimationFrame(tick);
}
}
const timeoutID: TimeoutID = {
id: requestAnimationFrame(tick),
};
return timeoutID;
}