diff --git a/src/tracing/SwapEventTimestampTracker.test.ts b/src/tracing/SwapEventTimestampTracker.test.ts index 7f5854d1ea..23f4cd8fdd 100644 --- a/src/tracing/SwapEventTimestampTracker.test.ts +++ b/src/tracing/SwapEventTimestampTracker.test.ts @@ -1,7 +1,7 @@ import { SwapEventTimestampTracker, SwapEventType } from './SwapEventTimestampTracker' jest.mock('./utils', () => ({ - calculateElapsedTimeWithPerformanceMark: (mark: string) => { + calculateElapsedTimeWithPerformanceMarkMs: (mark: string) => { switch (mark) { case SwapEventType.FIRST_SWAP_ACTION: return 100 diff --git a/src/tracing/SwapEventTimestampTracker.ts b/src/tracing/SwapEventTimestampTracker.ts index 52e52aedc5..c936363e0e 100644 --- a/src/tracing/SwapEventTimestampTracker.ts +++ b/src/tracing/SwapEventTimestampTracker.ts @@ -1,4 +1,4 @@ -import { calculateElapsedTimeWithPerformanceMark } from './utils' +import { calculateElapsedTimeWithPerformanceMarkMs } from './utils' // These events should happen in this order. export enum SwapEventType { @@ -18,6 +18,7 @@ export enum SwapEventType { export class SwapEventTimestampTracker { private static _instance: SwapEventTimestampTracker + private createdAt = Date.now() private constructor() { // Private constructor to prevent direct construction calls with the `new` operator. } @@ -36,7 +37,7 @@ export class SwapEventTimestampTracker { public setElapsedTime(eventType: SwapEventType): number | undefined { if (this.timestamps.has(eventType)) return undefined - const elapsedTime = calculateElapsedTimeWithPerformanceMark(eventType) + const elapsedTime = calculateElapsedTimeWithPerformanceMarkMs(eventType, this.createdAt) if (elapsedTime) { this.timestamps.set(eventType, elapsedTime) } diff --git a/src/tracing/utils.ts b/src/tracing/utils.ts index bef8bf6c4c..f74939ee72 100644 --- a/src/tracing/utils.ts +++ b/src/tracing/utils.ts @@ -1,9 +1,18 @@ /** - * Returns the time elapsed between page load and now. + * Returns the time elapsed between page load and now in milliseconds. * @param markName the identifier for the performance mark to be created and measured. */ -export function calculateElapsedTimeWithPerformanceMark(markName: string): number | undefined { +export function calculateElapsedTimeWithPerformanceMarkMs( + markName: string, + fallbackStartTime?: number +): number | undefined { const elapsedTime = performance.mark(markName) - if (!elapsedTime) return undefined - return elapsedTime.startTime + if (elapsedTime) { + return elapsedTime.startTime + } + if (fallbackStartTime) { + // On some browsers like iOS WebViews, performance.mark is not supported. + return Date.now() - fallbackStartTime + } + return undefined }