Skip to content Skip to sidebar Skip to footer

Count Down Timer Speeds Up

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 wo

Solution 1:

elseif(seconds==0)
        {
            // you should stop the timer here, and clear the intervalmyStopFunction();
            document.getElementById("timeExpired").innerHTML = "Time expired!";
        }

Edit: A side note

It is better to pass the function tick to the interval, rather than a string to evaluate. Using eval is generally a dangerous thing to do, and less efficient.

setInterval(tick, 1000)

Edit: Another side note

You can write the tick function a lot less verbosely (and without the extra variable seconds)

functiontick(){
        document.getElementById("countDown").innerHTML = timeInSecs;
        if(! timeInSecs--){
            myStopFunction()                
            document.getElementById("timeExpired").innerHTML = "Time expired!";
        }
    }

Solution 2:

I think you should use variable second instead of timeInSeconds--, in the tick() function.

Because you have given the value of timeInSeconds to seconds. Maybe this will help.

Solution 3:

I don't think you're clearing the interval when you reach 0.

You defined myStopFUnction() but probably never call it when seconds == 0.

Try:

elseif (seconds == 0) {
    document.getElementById("timeExpired").innerHTML = "Time expired!";
    myStopFunction();
}

Also, you should use ===

Solution 4:

var timeInSecs;
var ticker;
functionstartTimer(secs) 
{
    timeInSecs = secs;
}

functiontick() {
    var seconds = timeInSecs;
    if (seconds > 0) 
      timeInSecs--;
    elseif (seconds == 0) 
    {
        document.getElementById("timeExpired").innerHTML = "Time expired!";
    }
    document.getElementById("countDown").innerHTML = seconds;
    ticker = setInterval("tick()", 1000); // every second
}

functionmyStopFunction() 
{
    clearInterval(ticker);
} ​

Post a Comment for "Count Down Timer Speeds Up"