stopwatch / public /shared.js
krishgokul92's picture
Update public/shared.js
160c3f2 verified
raw
history blame contribute delete
912 Bytes
export function formatTime(ms) {
// Truncate to show only seconds and hundredths (SS.hh)
const totalMs = Math.max(0, Math.floor(ms));
const seconds = Math.floor((totalMs / 1000) % 60);
const hundredths = Math.floor((totalMs % 1000) / 10); // truncate, not round
const S = seconds.toString().padStart(2, "0");
const H = hundredths.toString().padStart(2, "0");
return `${S}.${H}`;
}
export function createSmoothRenderer({ setText }) {
let baseElapsedMs = 0;
let t0 = performance.now();
let running = false;
function applyServerState({ running: run, elapsedMs }) {
running = run;
baseElapsedMs = elapsedMs;
t0 = performance.now();
}
function loop() {
const now = performance.now();
const ms = baseElapsedMs + (running ? now - t0 : 0);
setText(formatTime(ms));
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
return { applyServerState };
}