mirror of
https://github.com/hex248/ob248.com.git
synced 2026-02-07 18:23:04 +00:00
is now realtime, using AnimationFrames
This commit is contained in:
@@ -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>
|
||||||
|
|||||||
Reference in New Issue
Block a user