Skip to content

Commit e33cc3b

Browse files
author
John Doe
committed
refactor: adjust timeOrigin logic
1 parent db25345 commit e33cc3b

File tree

2 files changed

+14
-8
lines changed

2 files changed

+14
-8
lines changed

packages/utils/src/lib/clock-epoch.ts

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,12 @@ export type EpochClockOptions = {
2525
pid?: number;
2626
tid?: number;
2727
};
28+
29+
type MaybePerformance = typeof performance & {
30+
timeOrigin?: number;
31+
now?: number;
32+
};
33+
2834
/**
2935
* Creates epoch-based clock utility.
3036
* Epoch time has been the time since January 1, 1970 (UNIX epoch).
@@ -36,12 +42,12 @@ export function epochClock(init: EpochClockOptions = {}) {
3642
const tid = init.tid ?? threadId;
3743

3844
const timeOriginMs = hasTimeOrigin()
39-
? (performance as { timeOrigin: number | undefined }).timeOrigin
40-
: undefined;
45+
? (performance as MaybePerformance).timeOrigin
46+
: Date.now();
4147

4248
const epochNowUs = (): Microseconds => {
4349
if (hasTimeOrigin()) {
44-
return msToUs(performance.timeOrigin + performance.now());
50+
return msToUs(timeOriginMs + performance.now());
4551
}
4652
return msToUs(Date.now());
4753
};
@@ -51,10 +57,10 @@ export function epochClock(init: EpochClockOptions = {}) {
5157
const fromEpochMs = msToUs;
5258

5359
const fromPerfMs = (perfMs: Milliseconds): Microseconds => {
54-
if (timeOriginMs === undefined) {
55-
return epochNowUs() - msToUs(performance.now() - perfMs);
60+
if (hasTimeOrigin()) {
61+
return msToUs(timeOriginMs + perfMs);
5662
}
57-
return msToUs(timeOriginMs + perfMs);
63+
return epochNowUs() - msToUs(performance.now() - perfMs);
5864
};
5965

6066
const fromEntryStartTimeMs = fromPerfMs;

packages/utils/src/lib/clock-epoch.unit.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ describe('epochClock', () => {
6262
timeOrigin: undefined,
6363
});
6464
const c = epochClock();
65-
expect(c.timeOriginMs).toBeUndefined();
65+
expect(c.timeOriginMs).toBe(1_000_000);
6666
expect(c.epochNowUs()).toBe(1_000_000_000); // Date.now() * 1000 when performance unavailable
6767
});
6868

@@ -72,7 +72,7 @@ describe('epochClock', () => {
7272
timeOrigin: undefined,
7373
});
7474
const c = epochClock();
75-
expect(c.timeOriginMs).toBeUndefined();
75+
expect(c.timeOriginMs).toBe(1_000_000);
7676
expect(c.fromPerfMs(100)).toBe(500_100_000); // epochNowUs() - msToUs(performance.now() - perfMs)
7777
});
7878

0 commit comments

Comments
 (0)