(HTML)
<div >
<div >
<div >
<h3>Days until my 22nd birthday</h3>
</div>
<div >
<div id="timeDay"><p></p></div>
<div id="timeHours"></div>
<div id="timeMinutes"></div>
<div id="timeSeconds"></div>
</div>
</div>
</div>
<script src="js/main.js"></script>
(javascript)
var birthdayDate = new Date('Jan 04, 2024 00:01:00');
var currentTime = new Date();
var timeLeft = birthdayDate - currentTime; (for current day)
var suspectedDays = document.getElementById("timeDay");
var suspectedHours = document.getElementById("timeHours");
var suspectedMins = document.getElementById("timeMinutes");
var suspectedSecs = document.getElementById("timeSeconds");
function getTime(){
//making the computer do math to get current time//
var d = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
var h = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var m = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
var s = Math.floor((timeLeft % (1000 * 60)) / 1000);
suspectedDays.innerHTML = d;
suspectedHours.innerHTML = h;
suspectedMins.innerHTML = m;
suspectedSecs.innerHTML = s;
}
setTimeout(getTime, 1000); //<-- Does not work
getTime(birthdayDate, currentTime(current time), timeLeft);
I was recommended to use the interval command but it does not go to plan and the countdown freezes. I looked at other examples but thus end up on the same problem as before. my freidd even looked at this and was stumped.
CodePudding user response:
Consider moving var currentTime
and var timeLeft
into the function getTime
so they actually get re-evaluated each time the getTime
function runs. As written it seems like this will write the same time to the elements every time the function runs.
CodePudding user response:
you need to put currentTime
in the function getTime()
so that getTime
methods can calculate remain time whenever called.
function getTime(){
var currentTime = new Date();
var timeLeft = birthdayDate - currentTime;
var d = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
var h = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var m = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
var s = Math.floor((timeLeft % (1000 * 60)) / 1000);
suspectedDays.innerHTML = d;
suspectedHours.innerHTML = h;
suspectedMins.innerHTML = m;
suspectedSecs.innerHTML = s;
}