I'm trying to create a countdown timer for quizzes that students can take on a website. The time limit would be 2 hours but for some reason I can only get my code to decrement minutes, not hours. What am I doing wrong here?
function startTimer(duration, display) {
var start = Date.now(),
diff,
hours,
minutes,
seconds;
function timer() {
diff = duration - (((Date.now() - start) / 1000) | 0);
hours = 2;
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = hours + ":" + minutes + ":" + seconds;
if (diff <= 0) {
start = Date.now() + 1000;
}
};
timer();
setInterval(timer, 1000);
}
window.onload = function() {
var display = document.querySelector('#time');
startTimer(seconds, display);
};
<div>Time remaining: <span id="time">2:00:00</span></div>
hoursto2and never changing it. Shouldn't you be getting the hours fromdiffjust like you are the minutes and seconds?startTimer(seconds, display)is incorrect.secondsis undefined.secondsonly exists in the timer function, so you should also setsecondsas a global variable.