refactor countdown update

to prepare displaying multiple coutndowns
master
lub 2 days ago
parent 437e6946d8
commit 8b32359c47

@ -8,11 +8,12 @@
<link rel="stylesheet" type="text/css" href="main.css?1602704189"> <link rel="stylesheet" type="text/css" href="main.css?1602704189">
<span id="output">
<span id="days">∞∞</span> Days<br> ∞∞ Days<br>
<span id="hours">∞∞</span> Hours<br> ∞∞ Hours<br>
<span id="minutes">∞∞</span> Minutes<br> ∞∞ Minutes<br>
<span id="seconds">∞∞</span> Seconds<br> ∞∞ Seconds<br>
</span>
<script src="main.js?1602704189"></script> <script src="main.js?1602704189"></script>

@ -1,11 +1,9 @@
const target = new Date(location.hash.substr(1));
const second = 1000; const second = 1000;
const minute = second*60; const minute = second*60;
const hour = minute*60; const hour = minute*60;
const day = hour*24; const day = hour*24;
const update_countdown = () => { const countdown = (target) => {
const now = new Date(); const now = new Date();
const diff = target - now; const diff = target - now;
@ -15,15 +13,24 @@ const update_countdown = () => {
timeleft.minutes = Math.trunc(diff%day%hour/minute); timeleft.minutes = Math.trunc(diff%day%hour/minute);
timeleft.seconds = Math.trunc(diff%day%hour%minute/second); timeleft.seconds = Math.trunc(diff%day%hour%minute/second);
Object.keys(timeleft).forEach((unit) => { const formatted = Object.keys(timeleft).map((unit) => {
// retrieve value, cast it to string and optionally pad it with a leading 0 // retrieve value, cast it to string and optionally pad it with a leading 0
const value = timeleft[unit] return timeleft[unit]
.toString() .toString()
.padStart(2, '0'); .padStart(2, '0');
document.getElementById(unit).innerHTML = value;
}); });
return `
${formatted[0]} Days<br>
${formatted[1]} Hours<br>
${formatted[2]} Minutes<br>
${formatted[3]} Seconds<br>
`;
}; };
update_countdown(); const hash_date = new Date(location.hash.substr(1))
setInterval(update_countdown, 500); const update_all = () => {
document.getElementById('output').innerHTML = countdown(hash_date);
}
update_all();
setInterval(update_all, 500);
Loading…
Cancel
Save