In this http://jsfiddle.net/kuox9ax2/ I have a timer that counts down.
- When it reaches zero, it starts over. It shouldn't do that.
- As JS is asynchronous I can't figure out how to get it to call a function only when it have reached zero.
I have tried to as return true
in startTimer()
, but then I run into that JS is asynchronous, so it returns true right away.
Can someone show how to solve these two issues?
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function() {
var time = 5, display = document.querySelector('#time');
var isDone = startTimer(time, display);
if (isDone) {
alert("a");
}
};
<div>Timeout in <span id="time">00:00</span> minutes</div>