I have a timer that counts down every second. The timer is used for a game: the user has up to 15 seconds
to answer to a question. Let’s say the game has 10 questions. The timer works great for the first question
, but then, speeds up more and more with every question. Any suggestion is more then welcome. Thank you!
Code is here:
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = secs;
ticker = setInterval("tick()", 1000); // every second
}
function tick() {
var seconds = timeInSecs;
if (seconds > 0) {
timeInSecs--;
}
else if (seconds == 0) {
document.getElementById("timeExpired").innerHTML = "Time expired!";
}
document.getElementById("countDown").innerHTML = seconds;
}
function myStopFunction() {
clearInterval(ticker);
}
Edit: A side note
It is better to pass the function
tickto the interval, rather than a string to evaluate. Using eval is generally a dangerous thing to do, and less efficient.Edit: Another side note
You can write the tick function a lot less verbosely (and without the extra variable
seconds)