I'm very new to Javascript and I found myself stuck with this issue. I want to make this countdown repeat after the time runs out, however I'm not really sure how to do it, and my attempts to make it work failed. Would appreciate help how to do it, Thanks.
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) {
// here's the problem. not sure how to make it repeat
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
Tried using clearInterval() and setTimeout() but instead of it working the countdown either went past 00:00 (00:0-1 and so on) or just didn't work at all.
CodePudding user response:
You can reset timer
:
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);
}
CodePudding user response:
What you're describing is a forever countdown.
So we just need to note startTime
and currentTime
and put them in an infinite timer loop. Then, we do some math to reformat the result as a countdown from your set duration.
I use elapsed = (currentTime - startTime) / 1000
to calculate the elapsed time in seconds. Then, I elapsed % duration
to make the counter stop at the duration and reset. Finally, I flip the math so instead of counting up, it counts down.
Below is a fully working example that uses jQuery.
function startTimer(duration, display) {
let startTime = Date.now();
setInterval(function() {
let currentTime = Date.now();
let elapsed = Math.floor((currentTime - startTime) / 1000);
let countdown = duration - (elapsed % duration);
let minutes = Math.floor(countdown / 60).toString().padStart(2, "0");
let seconds = (countdown % 60).toString().padStart(2, "0");
display.text(minutes ":" seconds);
}, 1000 );
}
let fiveMinutes = 60 * 5;
let display = $("#time");
startTimer(fiveMinutes, display);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label id="time">mm:ss</label>