2
2
* License, v. 2.0. If a copy of the MPL was not distributed with this
3
3
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
4
5
- import { NAVIGATION_TIMING_FIELDS } from './timing-fields'
5
+ import { NAVIGATION_TIMING_FIELDS } from './timing-fields' ;
6
6
7
7
/**
8
8
* Small util for determining if a browser went to sleep.
9
9
*/
10
10
class SleepDetection {
11
-
12
11
constructor ( ) {
13
12
this . sleepDetected = false ;
14
- this . lastTime = Date . now ( ) ;
13
+ this . lastTime = Date . now ( ) ;
15
14
this . iid = '' ;
16
15
}
17
16
18
17
startSleepDetection ( ) {
19
18
this . iid = setInterval ( ( ) => {
20
- if ( this . sleepDetected ) {
21
- clearInterval ( this . iid ) ;
22
- return ;
23
- }
19
+ if ( this . sleepDetected ) {
20
+ clearInterval ( this . iid ) ;
21
+ return ;
22
+ }
24
23
25
- const currentTime = Date . now ( ) ;
26
- if ( currentTime > ( this . lastTime + 2000 * 2 ) ) { // ignore small delays
27
- this . sleepDetected = true ;
28
- }
29
- this . lastTime = currentTime ;
30
- } , 2000 ) ;
31
- }
24
+ const currentTime = Date . now ( ) ;
25
+ if ( currentTime > this . lastTime + 2000 * 2 ) {
26
+ // ignore small delays
27
+ this . sleepDetected = true ;
28
+ }
29
+ this . lastTime = currentTime ;
30
+ } , 2000 ) ;
31
+ }
32
32
}
33
33
34
34
/**
@@ -39,7 +39,6 @@ class SleepDetection {
39
39
* and the metrics collected will be wildly off.
40
40
*/
41
41
class PerformanceFallback {
42
-
43
42
constructor ( ) {
44
43
this . unreliable = true ;
45
44
this . timeOrigin = Date . now ( ) ;
@@ -69,7 +68,7 @@ export function getFallbackPerformanceApi() {
69
68
/**
70
69
* Provides the browser's performance api.
71
70
*/
72
- export function getRealPerformanceApi ( ) {
71
+ export function getRealPerformanceApi ( ) {
73
72
// eslint-disable-next-line no-undef
74
73
return window . performance ;
75
74
}
@@ -79,10 +78,15 @@ export function getRealPerformanceApi () {
79
78
* of it to support minimal functionality required by speed trap.
80
79
*/
81
80
export function getPerformanceApi ( ) {
82
- // eslint-disable-next-line no-undef
83
- if ( ! ! window . performance && typeof window . performance . now === 'function' ) {
84
- return getRealPerformanceApi ( ) ;
85
- }
81
+ const api = getRealPerformanceApi ( ) ;
82
+ // If the api can produce a time origin and a valid now, let's use it.
83
+ try {
84
+ const check = api . timeOrigin + api . now ( ) ;
85
+ if ( typeof check === 'number' && check > 0 ) {
86
+ return api ;
87
+ }
88
+ } catch ( err ) { }
86
89
90
+ // Otherwise return the fallback api
87
91
return getFallbackPerformanceApi ( ) ;
88
92
}
0 commit comments