Skip to content

Instantly share code, notes, and snippets.

@nuggetnchill
Last active December 21, 2020 20:12
Show Gist options
  • Save nuggetnchill/1941387c1d8f7dbf60af45fa0ab9e75b to your computer and use it in GitHub Desktop.
Save nuggetnchill/1941387c1d8f7dbf60af45fa0ab9e75b to your computer and use it in GitHub Desktop.
Countdown Timer with JS
// JavaScript Countdown Timer
let endDate = new Date("Dec 25, 2020 00:00:00").getTime();
const timer = setInterval(tick, 1000)
function tick () {
let currentTime = new Date().getTime();
let timeLeft = endDate - currentTime;
if (timeLeft > 0) {
// Calculate Days
let daysLeft = Math.floor(timeLeft / (1000*60*60*24));
if (daysLeft < 10){
daysLeft = "0" + daysLeft;
}
// Calculate Hrs
let hoursLeft = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
if (hoursLeft < 10){
hoursLeft = "0" + hoursLeft;
}
// Calculate Mins
let minLeft = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
if (minLeft < 10){
minLeft = "0" + minLeft;
}
// Calculate Secs
let secLeft = Math.floor((timeLeft % (1000 * 60)) / 1000);
if (secLeft < 10){
secLeft = "0" + secLeft;
}
// TIME STRING for display
let displayTime = `Christmas countdown ${daysLeft} days ${hoursLeft} hrs ${minLeft} mins ${secLeft} secs `;
document.querySelector('.countdown').innerText = displayTime;
}
}
// create a <div> with className="countdown" for result to display
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment