fix: use Date as a performance tracker fallback (#7349)

This commit is contained in:
eddie 2023-09-22 09:40:25 -07:00 committed by GitHub
parent 59e7a2867a
commit df6c44d2c4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 17 additions and 7 deletions

@ -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

@ -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)
}

@ -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
if (elapsedTime) {
return elapsedTime.startTime
}
if (fallbackStartTime) {
// On some browsers like iOS WebViews, performance.mark is not supported.
return Date.now() - fallbackStartTime
}
return undefined
}