@@ -147,13 +147,14 @@ export const browserPerformanceTimeOrigin = ((): number | undefined => {
147147 }
148148
149149 const threshold = 3600 * 1000 ;
150+ const performanceNow = performance . now ( ) ;
151+ const dateNow = Date . now ( ) ;
150152
151- const timeOriginIsReliable =
152- performance . timeOrigin && Math . abs ( performance . timeOrigin + performance . now ( ) - Date . now ( ) ) < threshold ;
153- if ( timeOriginIsReliable ) {
154- _browserPerformanceTimeOriginMode = 'timeOrigin' ;
155- return performance . timeOrigin ;
156- }
153+ // if timeOrigin isn't available set delta to threshold so it isn't used
154+ const timeOriginDelta = performance . timeOrigin
155+ ? Math . abs ( performance . timeOrigin + performanceNow - dateNow )
156+ : threshold ;
157+ const timeOriginIsReliable = timeOriginDelta < threshold ;
157158
158159 // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin
159160 // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.
@@ -163,14 +164,22 @@ export const browserPerformanceTimeOrigin = ((): number | undefined => {
163164 // eslint-disable-next-line deprecation/deprecation
164165 const navigationStart = performance . timing && performance . timing . navigationStart ;
165166 const hasNavigationStart = typeof navigationStart === 'number' ;
166- const navigationStartIsReliable =
167- hasNavigationStart && Math . abs ( navigationStart + performance . now ( ) - Date . now ( ) ) < threshold ;
168- if ( navigationStartIsReliable ) {
169- _browserPerformanceTimeOriginMode = 'navigationStart' ;
170- return navigationStart ;
167+ // if navigationStart isn't available set delta to threshold so it isn't used
168+ const navigationStartDelta = hasNavigationStart ? Math . abs ( navigationStart + performanceNow - dateNow ) : threshold ;
169+ const navigationStartIsReliable = navigationStartDelta < threshold ;
170+
171+ if ( timeOriginIsReliable || navigationStartIsReliable ) {
172+ // Use the more reliable time origin
173+ if ( timeOriginDelta <= navigationStartDelta ) {
174+ _browserPerformanceTimeOriginMode = 'timeOrigin' ;
175+ return performance . timeOrigin ;
176+ } else {
177+ _browserPerformanceTimeOriginMode = 'navigationStart' ;
178+ return navigationStart ;
179+ }
171180 }
172181
173182 // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.
174183 _browserPerformanceTimeOriginMode = 'dateNow' ;
175- return Date . now ( ) ;
184+ return dateNow ;
176185} ) ( ) ;
0 commit comments