Auto refresh
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
(function () {
|
||||
const body = document.body;
|
||||
if (!body) return;
|
||||
|
||||
if (body.dataset.autoRefresh !== "true") return;
|
||||
|
||||
const statusEl = document.getElementById("refreshStatus");
|
||||
|
||||
const intervalSeconds = Number(body.dataset.collectIntervalSeconds || "0");
|
||||
if (!Number.isFinite(intervalSeconds) || intervalSeconds <= 0) return;
|
||||
|
||||
const intervalMs = Math.max(60000, intervalSeconds * 1000);
|
||||
const graceMs = 8000;
|
||||
const timeFmt = new Intl.DateTimeFormat([], {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
second: "2-digit",
|
||||
});
|
||||
|
||||
function setStatus(lastRefreshAt, nextRefreshAt) {
|
||||
if (!statusEl) return;
|
||||
statusEl.textContent = `Last refresh: ${timeFmt.format(lastRefreshAt)} | Next refresh: ${timeFmt.format(nextRefreshAt)}`;
|
||||
}
|
||||
|
||||
function reloadWhenVisible() {
|
||||
if (document.visibilityState === "visible") {
|
||||
window.location.reload();
|
||||
return;
|
||||
}
|
||||
|
||||
function onVisibilityChange() {
|
||||
if (document.visibilityState !== "visible") return;
|
||||
document.removeEventListener("visibilitychange", onVisibilityChange);
|
||||
window.location.reload();
|
||||
}
|
||||
|
||||
document.addEventListener("visibilitychange", onVisibilityChange);
|
||||
}
|
||||
|
||||
function scheduleAlignedRefresh() {
|
||||
const now = Date.now();
|
||||
const nextBoundary = Math.ceil(now / intervalMs) * intervalMs;
|
||||
const runAt = nextBoundary + graceMs;
|
||||
setStatus(new Date(now), new Date(runAt));
|
||||
const delay = Math.max(1000, runAt - now);
|
||||
|
||||
window.setTimeout(reloadWhenVisible, delay);
|
||||
}
|
||||
|
||||
scheduleAlignedRefresh();
|
||||
})();
|
||||
Reference in New Issue
Block a user