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!
You can't resume a timer - what you can do is capture the difference between how much time has passed and how much is remaining when you "pause" the timer, and then when you want to "unpause" you set a new timer for that remainder.
Consider this snippet from a backbone project I did ages ago: