Hello, Users!
I am trying to learn more JavaScript and I am in the process of attempting to create two countdown timers to two separate events. The code I am currently using is a modified countdown timer from W3C to fit my needs. I was wondering how I could make this code more efficient. I’m essentially hoping to create one function to run and display two countdown timers across two separate HTML elements.
My current method works, however, I feel like it isn’t very well written. Note: I’m still pretty new to JavaScript so it would be appreciated if any code you offer had some comments in to allow me to comprehend the purpose of it.
var countDownDate = new Date("Apr 14, 2017 00:00:01").getTime();
var newCountdown = new Date("Jul 07, 2017 00:00:01").getTime();
var x = setInterval(function() {
var timeNow = new Date().getTime();
var distance = countDownDate - timeNow;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("displayCountdown").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
var distance = newCountdown - timeNow;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("displaySecondCountdown").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
}, 1000);