is now realtime, using AnimationFrames

This commit is contained in:
Oliver Bryan
2025-10-29 00:40:18 +00:00
parent e2b546fc49
commit 21d4f7f9fc

View File

@@ -6,17 +6,18 @@ const uniqueId = `time-since-${Math.random().toString(36).substring(2, 9)}`;
<span id={uniqueId} data-date={date.getTime()}></span> <span id={uniqueId} data-date={date.getTime()}></span>
<script define:vars={{ uniqueId, dateMS: date.getTime() }}> <script define:vars={{ uniqueId, dateMS: date.getTime() }}>
const currentTimeMS = Math.floor(new Date().getTime()); let rafId = null;
let interval = 1; // ms function roundToDp(num, dp) {
let msElapsed = 0; const factor = Math.pow(10, dp);
return Math.floor(num * factor) / factor;
}
function updateTimeSince() { function render(milliseconds) {
let years = roundToDp( const years = roundToDp(
(currentTimeMS - dateMS + msElapsed) / (60 * 60 * 24 * 365.25 * 1000), milliseconds / (60 * 60 * 24 * 365.25 * 1000),
2 2
); );
let milliseconds = currentTimeMS - dateMS + msElapsed;
const element = document.getElementById(uniqueId); const element = document.getElementById(uniqueId);
if (element) { if (element) {
@@ -24,15 +25,38 @@ const uniqueId = `time-since-${Math.random().toString(36).substring(2, 9)}`;
} }
} }
function roundToDp(num, dp) { function tick() {
const factor = Math.pow(10, dp); const now = Date.now();
return Math.floor(num * factor) / factor; const milliseconds = now - dateMS;
render(milliseconds);
rafId = requestAnimationFrame(tick);
} }
updateTimeSince(); render(Math.max(0, Date.now() - dateMS));
rafId = requestAnimationFrame(tick);
setInterval(() => { function onVisibilityChange() {
msElapsed += interval; if (document.hidden) {
updateTimeSince(); if (rafId) {
}, interval); cancelAnimationFrame(rafId);
rafId = null;
}
} else {
if (!rafId) {
rafId = requestAnimationFrame(tick);
}
}
}
function cleanup() {
if (rafId) {
cancelAnimationFrame(rafId);
rafId = null;
}
window.removeEventListener("visibilitychange", onVisibilityChange);
window.removeEventListener("unload", cleanup);
}
window.addEventListener("visibilitychange", onVisibilityChange);
window.addEventListener("unload", cleanup);
</script> </script>