I'm trying to make an infinitely looping countdown timer in JavaScript. I'm able to get the countdowns functioning as intended, but can't get them to reset properly once they hit 0/go below 0.
I should have specified, I apologize, for the first timer "mcReset" I need to reset the date to 7 days from the originally specified date when the timer hits 0.
For the second timer "onyReset" I need to reset the date to 5 days from the originally specified date when the timer hits 0.
So for example mcReset (Oct 14 9:28:00) would become Oct 21 9:28:00 and onyReset (Oct 17, 2019 12:00:00) would become Oct 22, 2019 12:00:00 and the countdown would infinitely loop from that.
I'm not super familiar with JavaScript so any help is appreciated :)
Here's the code:
// Set the date we're counting down to
var mcReset = new Date("Oct 14, 2019 9:28:00").getTime();
var onyReset = new Date("Oct 17, 2019 12:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = mcReset - now;
var onyDistance = onyReset - now;
// Time calculations for days, hours, minutes and seconds
var mcDays = Math.floor(distance / (1000 * 60 * 60 * 24));
var onyDays = Math.floor(onyDistance / (1000 * 60 * 60 * 24));
var mcHours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var onyHours = Math.floor((onyDistance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var mcMinutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var onyMinutes = Math.floor((onyDistance % (1000 * 60 * 60)) / (1000 * 60));
var mcSeconds = Math.floor((distance % (1000 * 60)) / 1000);
var onySeconds = Math.floor((onyDistance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = mcDays + "d " + mcHours + "h "
+ mcMinutes + "m " + mcSeconds + "s ";
document.getElementById("ony").innerHTML = onyDays + "d " + onyHours + "h "
+ onyMinutes + "m " + onySeconds + "s ";
// If the count down is over, reset
if (distance < 0) {
// do something here?
// not sure what
}
}, 1000);
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p id="demo"></p>
<p id="ony"></p>
</body>
</html>