Last active
January 21, 2022 13:23
-
-
Save peterkarn/339adf714a256895653715d1ca2da8bf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Document</title> | |
</head> | |
<body> | |
<section class="timer-section"> | |
<div class="timer"> | |
<div class="timer-block"> | |
<span class="days">12</span> | |
</div> | |
<div class="timer-block"> | |
<span class="hours">20</span> | |
</div> | |
<div class="timer-block"> | |
<span class="minutes">35</span> | |
</div> | |
<div class="timer-block"> | |
<span class="seconds">43</span> | |
</div> | |
</div> | |
</section> | |
</body> | |
<script> | |
const deadline = '2022-04-01'; | |
const getTimeRmaining = (endtime) => { | |
const diffMS = Date.parse(endtime) - Date.parse(new Date()); //diff in MS between deadline and current date | |
const days = Math.floor(diffMS / (1000 * 60 * 60 * 24)); //MS in a one day | |
const hours = Math.floor(((diffMS / 1000 * 60 * 60) % 24)); // trim number of days, keft only hours | |
const minutes = Math.floor((diffMS / 1000 / 60) % 60); // trim number of hours, keft only minutes | |
const seconds = Math.floor(diffMS / 1000 % 60); // seconds | |
return { | |
'total': diffMS, | |
'days': days, | |
'hours': hours, | |
'minutes': minutes, | |
'seconds': seconds | |
}; | |
} | |
const setClock = (selector, endtime) => { | |
const timer = document.querySelector(selector); | |
const days = timer.querySelector('.days'); | |
const hours = timer.querySelector('.hours'); | |
const minutes = timer.querySelector('.minutes'); | |
const seconds = timer.querySelector('.seconds'); | |
const timeInterval = setInterval(updateClock, 1000); | |
function updateClock() { | |
const diff = getTimeRmaining(endtime); | |
days.innerHTML = diff.days; | |
hours.innerHTML = diff.hours; | |
minutes.innerHTML = diff.minutes; | |
seconds.innerHTML = diff.seconds; | |
if (diff.total <= 0) { | |
clearIntrval(timeInterval); | |
} | |
} | |
}; | |
setClock('.timer', deadline); | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment