Onclick Countdown for an Alarmclock does not stop properly. It stops at "-1:0" and not 0:00 as planed. Tryed to solve the Problem by changing the "> < =" Operators but i dont get it right. Maybe someone can help me with that.
function startTimer() {
let startTime = new Date().getTime();
let fiveMinutes = 5 * 1 * 1000;
let endTime = startTime + fiveMinutes;
var countdown = setInterval(function count() {
let timeLeft = endTime - new Date().getTime();
let minutes = timeLeft / (1000 * 60);
minutes = Math.floor(minutes);
let seconds = (timeLeft / 1000) % 60;
seconds = Math.round(seconds);
let text = minutes + ':' + seconds;
timer.innerHTML = text;
if ((minutes <= 0) && (seconds <= 0)) {
clearInterval(countdown);
}
}, 1000);
}
<div class="timer center margin-top" id="timer">
00:05
</div>
<div class="button center">
<img onclick="startTimer()" img src="img/btn.png" />
</div>
Your problem is only using Math.floor(minutes).
try to use Math.round(minutes)
this is code for solve your problem :
function startTimer() {
let startTime = new Date().getTime();
let fiveMinutes = 5 * 1 * 1000;
let endTime = startTime + fiveMinutes;
var countdown = setInterval(function () {
let timeLeft = endTime - new Date().getTime();
let minutes = timeLeft / (1000 * 60);
minutes = Math.round(minutes);
let seconds = (timeLeft / 1000) % 60;
seconds = Math.round(seconds);
let text = minutes + ':' + seconds;
timer.innerHTML = text;
if ((minutes <= 0) && (seconds <= 0)) {
clearInterval(countdown);
}
}, 1000);
}
<div class="timer center margin-top" id="timer">
00:05
</div>
<div class="button center">
<img onclick="startTimer()" img src="img/btn.png" alt="button start" />
</div>
function startTimer() {
let startTime = new Date().getTime();
// If its five minute 5 * 60 * 1000;
let fiveSeconds = 5 * 1000;
let endTime = startTime + fiveSeconds;
var countdown = setInterval(function count() {
let timeLeft = endTime - new Date().getTime();
let minutes = Math.floor((timeLeft / (1000 * 60)) % 60);
let seconds = Math.floor((timeLeft / 1000) % 60);
// Once test is passed do the DOM manipulation
let text = minutes + ':' + seconds;
timer.innerHTML = text;
if ((minutes <= 0) && (seconds === 0)) {
return clearInterval(countdown);
}
}, 1000);
}
<div class="timer center margin-top" id="timer">
5:00
</div>
<div class="button center">
<button onclick="startTimer()">Start</button>
</div>