-
Notifications
You must be signed in to change notification settings - Fork 0
/
TimeProvider.ts
75 lines (66 loc) · 2.02 KB
/
TimeProvider.ts
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
/*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2016-Present Datadog, Inc.
*/
/**
* A Timestamp structure holding the
*/
export type Timestamp = {
// Result of Date API. Unix timestamp in ms.
unix: number;
// Result of performance.now API. Timestamp in ms (with microsecond precision)
// since JS context start.
react_native: number | null;
};
/**
* Simple class providing timestamps in milliseconds.
* If available, it will use the `performance.now()` method, and will fallback on `Date.now()` otherwise.
*/
export class TimeProvider {
private canUsePerformanceNow =
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
global.performance && typeof performance.now === 'function';
/** Keeps an average offset between the unix time and the provided timestamp. */
private baseOffset: number;
constructor() {
const timestamp = this.getTimestamp();
if (timestamp.react_native == null) {
this.baseOffset = 0;
} else {
this.baseOffset = timestamp.unix - timestamp.react_native;
}
}
getTimestamp(): Timestamp {
return {
unix: Date.now(),
react_native: this.performanceNow(),
};
}
now(): number {
const timestamp = this.getTimestamp();
if (timestamp.react_native == null) {
return timestamp.unix;
} else {
return this.baseOffset + timestamp.react_native;
}
}
getDebugInfo(): object {
return {
['baseOffset']: this.baseOffset,
['Date.now()']: Date.now(),
['performance.now()']: this.performanceNow(),
['now()']: this.now(),
};
}
private performanceNow(): number | null {
if (this.canUsePerformanceNow) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
return performance.now();
}
return null;
}
}
export const TimeProviderInstance = new TimeProvider();