Spaces:
Running
Running
File size: 1,101 Bytes
fb12607 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | export class NtpClockSync {
private offsetMs = 0;
async sync() {
try {
const start = performance.now();
const res = await fetch('https://worldtimeapi.org/api/timezone/Etc/UTC');
const data = await res.json();
const end = performance.now();
const rtt = end - start;
const serverTimeMs = new Date(data.utc_datetime).getTime();
// The server time was received at localTimeNow - (rtt/2) approximately
// So trueTimeNow = serverTimeMs + (rtt/2)
// offset = trueTimeNow - localTimeNow
const localTimeNow = Date.now();
const trueTimeNow = serverTimeMs + (rtt / 2);
this.offsetMs = trueTimeNow - localTimeNow;
console.log(`[Clock Sync] Local clock drift calculated: ${this.offsetMs}ms`);
} catch (err) {
console.warn('[Clock Sync] Failed. Processing will rely on relative starting stamps.');
this.offsetMs = 0;
}
}
getTrueTimeMs() {
return Date.now() + this.offsetMs;
}
}
|