Better way to create 2 countdowns?

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);

I’m surprised that the W3C would have example JavaScript code.

In any case, you’re not getting any error messages in your browsers dev tool console?
Seems that re-declaring the variables would be causing a problem.

There are errors in the console, but nothing relating to this script. Everything seems to be running just fine. The output is exactly what I expected, too: two separate countdown timers being displayed in two different HTML elements. Initially, I thought that redefining the variable “distance” half way through the script would give me an error, too.

<a href=““https://s2.postimg.org/flz6kgyd5/Screen_Shot_2017_02_17_at_05_51_30.png” target=”_blank">Timer 1

Timer 2

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.