pause countdown javascript jquery

728 views Asked by At

http://jsfiddle.net/vvccvvcc/mu45bptk/

how do I pause the timer? I want it to stop when it gets to 5 seconds

I tried this as seen in the fiddle

else {
        isWaiting = true;
        seconds--;

        if (seconds == 5) {
            seconds=seconds;}     




    }

does not work

2

There are 2 answers

0
Reza On BEST ANSWER

The timer is initialized by setInterval(GameTimer, 1000);

    if (seconds == 5) {
        clearInterval(countdownTimer);
    } else {
         seconds--;
    }

You will need to clear the interval in order to stop calling the function. Alternatively if you don't want to clear the interval you can say

    if (seconds > 5) {
         seconds--;
    }

The way you've written it, second is decreased regardless of the condition (since it's before the if statement) and therefore, second = second becomes irrelevant.

0
Jonathan Crowe On

Is this what you are looking for? Fiddle: http://jsfiddle.net/mu45bptk/2/

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

function GameTimer() {
    if (isWaiting) {
        return;   
    }
    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) {

        if (finalCountdown) {
            clearInterval(countdownTimer);
        } else {
            finalCountdown = true;
        }

    } else {             
        if (seconds == 5) {            
            isWaiting = true;  
        } else {
            seconds--;
        }




    }
}
countdownTimer = setInterval(GameTimer, 1000);

You need to set isWaiting only if seconds == 5 and then check isWaiting on every run of GameTimer()