Reputation: 73
I'm trying to create a countdown timer that counts down from a given time and when it reaches 0, it starts counting back up again.
My code works (after a lot of trial and error) however it's losing the first second after being initiated.
My thinking is that it's not an optimized solution and it's taking a second or more to initiate.
Is there a better way to achieve this?
Javascript:
function startCountdown() {
var setPlayers = ['Name 1', 'Name 2', 'Name 3'];
var playersIndex = 0;
var countdownState = 0;
var time = 5;
var messageEl = document.getElementById('message');
var timer = document.getElementById('timer');
var standUp = setInterval(function(){
// if countownState = 0, count down.
if(countdownState == 0){
// if all players have been, end the timer
if(playersIndex == setPlayers.length){
clearInterval(standUp);
messageEl.innerHTML = 'Finished!';
timer.innerHTML = '';
// if time reaches 0 switch the state and start counting up
} else if(time == 0) {
countdownState = 1;
timer.innerHTML = pad(parseInt(time/60,10)) + ':' + pad(++time%60);
// usual countdown
} else {
timer.innerHTML = pad(parseInt(time/60,10)) + ':' + pad(--time%60);
}
// if countownState = 1, count up.
} else {
timer.innerHTML = pad(parseInt(time/60,10)) + ':' + pad(++time%60);
}
}, 1000);
}
I'll have a seperate function that increments the player index and starts the timer again.
HTML
<div id="timer"></div>
<div id="message"></div>
When I load the page, the timer looks like it is starting from 4 instead of 5.
Upvotes: 1
Views: 256
Reputation: 193
I updated your interval call to be a separate function. This will require all of the variables to be moved out of the startCountdown function so that they are globals. There are better ways to do this, but it will solve your problem.
var setPlayers = ['Name 1', 'Name 2', 'Name 3'];
var playersIndex = 0;
var countdownState = 0;
var time = 5;
var messageEl = document.getElementById('message');
var timer = document.getElementById('timer');
function startCountdown()
{
countDown();
var standUp = setInterval(countDown, 1000);
}
function countDown()
{
// if countownState = 0, count down.
if(countdownState == 0)
{
// if all players have been, end the timer
if(playersIndex == setPlayers.length)
{
clearInterval(standUp);
messageEl.innerHTML = 'Finished!';
timer.innerHTML = '';
// if time reaches 0 switch the state and start counting up
}
else if(time == 0)
{
countdownState = 1;
timer.innerHTML = pad(parseInt(time/60,10)) + ':' + pad(++time%60);
// usual countdown
}
else
{
timer.innerHTML = pad(parseInt(time/60,10)) + ':' + pad(--time%60);
}
// if countownState = 1, count up.
}
else
{
timer.innerHTML = pad(parseInt(time/60,10)) + ':' + pad(++time%60);
}
}
Upvotes: 1