window.onload = function HRTTimer() { let interval = 1000; let times = getTimes(interval); let expected = times["expected"]; setTimeout(step, interval); function step() { const dt = Date.now() - expected; // the drift (positive for overshooting) if (dt > interval) { // something really bad happened. Maybe the browser (tab) was inactive? // possibly special handling to avoid futile "catch up" run } times["days"] = Math.round(expected / 1000 / 60 / 60 / 24); times["hours"] = (new Date(expected).getHours() + 6) % 24; times["minutes"] = new Date(expected).getMinutes(); times["seconds"] = new Date(expected).getSeconds(); if (document.getElementById("time_0") != null) { document.getElementById("time_0").textContent = times["days"] + " days, "; document.getElementById("time_1").textContent = times["hours"] + " hours, "; document.getElementById("time_2").textContent = times["minutes"] + " minutes, "; document.getElementById("time_3").textContent = "and " + times["seconds"] + " seconds"; } expected += interval; setTimeout(step, Math.max(interval - dt, 1000)); // take into account drift } }; function getTimes(interval) { let expected = Date.now() - new Date("December 11, 2020 00:00:00") + interval; let days = Math.floor(expected / 1000 / 60 / 60 / 24); let hours = new Date(expected).getHours(); let minutes = new Date(expected).getMinutes(); let seconds = new Date(expected).getSeconds(); return { expected: expected, days: days, hours: hours, minutes: minutes, seconds: seconds, }; }