From 8b370cfb82847e6e2d49becce2aa2e23669ac178 Mon Sep 17 00:00:00 2001 From: kajacx Date: Thu, 27 Jul 2023 11:17:54 +0200 Subject: [PATCH 1/2] Use one Date.now() call in wall clock This prevents a "bad" case when one first Date.now() call returns a different date than the second Date.now() call, which can be especially bad if the two dates "cross over" the millisecond boundary. --- packages/preview2-shim/lib/browser/clocks.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/preview2-shim/lib/browser/clocks.js b/packages/preview2-shim/lib/browser/clocks.js index 2f23127a5..89ba897b7 100644 --- a/packages/preview2-shim/lib/browser/clocks.js +++ b/packages/preview2-shim/lib/browser/clocks.js @@ -33,8 +33,9 @@ export const timezone = { export const wallClock = { now() { - const seconds = BigInt(Math.floor(Date.now() / 1e3)); - const nanoseconds = (Date.now() % 1e3) * 1e6; + let now = Date.now(); // in milliseconds + const seconds = BigInt(Math.floor(now / 1e3)); + const nanoseconds = (now % 1e3) * 1e6; return { seconds, nanoseconds }; }, From 2386a6005ca4243f69b7191a49480506291b157c Mon Sep 17 00:00:00 2001 From: kajacx Date: Thu, 27 Jul 2023 11:19:17 +0200 Subject: [PATCH 2/2] Multiply performance.now() by 1e6 instead of 1e9 performance.now() returns milliseconds, and we want nanoseconds, so we need to multiply by a million, not a billion. --- packages/preview2-shim/lib/browser/clocks.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/preview2-shim/lib/browser/clocks.js b/packages/preview2-shim/lib/browser/clocks.js index 89ba897b7..1500a4208 100644 --- a/packages/preview2-shim/lib/browser/clocks.js +++ b/packages/preview2-shim/lib/browser/clocks.js @@ -1,5 +1,6 @@ function _hrtimeBigint () { - return BigInt(Math.floor(performance.now() * 1e9)); + // performance.now() is in milliseconds, but we want nanoseconds + return BigInt(Math.floor(performance.now() * 1e6)); } let _hrStart = _hrtimeBigint();