I'm trying to implement a timer which does a countdown from 60 seconds. I am able to pause the timer when I click the pause button, but when I click it again to resume, it resets the timer back to 60 seconds.
Here's a snippet of the code:
var t = 0;
function pause_game(pause_button){
var elem = document.getElementById('pause_button');
var lastTime;
if (elem.value=="PAUSE"){
lastTime = clearTimeout(t);
elem.value = "RESUME";
}
if (elem.value=="RESUME"){
countdownTimer(lastTime);
elem.value = "PAUSE";
}
}
function countdownTimer(secs) {
var game_page = document.getElementById('game_page');
var start_page = document.getElementById('start_page');
var seconds = 60;
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "0" + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if(seconds > 0) {
t = setTimeout(tick, 1000);
}
else {
setTimeout(function () {
game_page.style.display = 'none';
start_page.style.display = 'block';
}, 1000)
}
tick();
}
Can't seem to figure out what went wrong. Help would be greatly appreciated. Thanks!
The
t
variable won't return current countdown value, it returns the setTimeout id, which used to cancel the timeout function.So you have to use another variable to record down the current countdown seconds and in the countDownTimer function, instead of assign 60 to seconds, assign the recorded current countdown seconds.
Or you can use a setInterval function to do the countdown job and set a pause boolean value to denote the status: