Skip to content Skip to sidebar Skip to footer

Game Timer Javascript

I'm creating a countdown timer. If seconds is equal to zero I have set 2 secs to var seconds. Please help. I need to stop the program from looping after getting the 2 seconds var i

Solution 1:

Here is your fixed code:

var isWaiting = false;
var isRunning = false;
var seconds = 10;
var countdownTimer;
var finalCountdown = false;

functionGameTimer() {
    var minutes = Math.round((seconds - 30) / 60);
    var remainingSeconds = seconds % 60;
    if (remainingSeconds < 10) {
        remainingSeconds = "0" + remainingSeconds;
    }
    document.getElementById('waiting_time').innerHTML = minutes + ":" + remainingSeconds;
    if (seconds == 0) {
        isRunning = true;
        seconds += 2;

        if (finalCountdown) {
            clearInterval(countdownTimer); // Clear the interval to stop the loop
        } else {
            finalCountdown = true; // This will allow the 2 additional seconds only once.
        }

    } else {
        isWaiting = true;
        seconds--;
    }
}
countdownTimer = setInterval(GameTimer, 1000); // Pass function reference, don't invoke it.

WORKING DEMO:http://jsfiddle.net/nEjL4/1/

Solution 2:

since i couldn't understand the code that's up in the question i wrote down my own timer. So take a look if it works out for you.

http://jsfiddle.net/9sEGz/

var m=getId('m'), s=getId('s'), btn=getId('btn'), status=getId('status'), inc =getId('inc') , dec =getId('dec'), interval=null, time=0, min=0;

btn.onclick = startCounter;
inc.onclick = incTime;
dec.onclick = decTime;

functionstartCounter() {

    if (time<=0) {
        status.textContent='Increase the timer first!';
        time=0;
        return;
    }
    status.textContent='Counting!';
    btn.textContent = 'Stop';
    btn.onclick = stopCounter;
    interval = setInterval(function(){
        time--;if (time<=0) {
            stopCounter();
            status.textContent='Time\'s Up';
        }
    setTime();        
    },200);
}

functionstopCounter() {
    btn.textContent = 'Start';
    btn.onclick = startCounter;
    status.textContent='Stopped!';
    if (interval) clearInterval(interval);
}

functionincTime(){
    time++;
    setTime();
}

functiondecTime(){
    time--;
    setTime();
}

functionsetTime() { 
        min= time/60;
        if (time<10) s.textContent= '0'+Math.floor(time%60);
        else s.textContent= Math.floor(time%60);
        if (min<0) m.textContent= '00';
        elseif (min<10) m.textContent= '0'+Math.floor(min);
        else m.textContent= Math.floor(min);
}

functiongetId(x) {
    return document.getElementById(x);
}

Post a Comment for "Game Timer Javascript"