I have the following function:
$(document).ready(function() {
$('#p').click(function() {
$('#s1').hide();
gameStart(); <-starts timer
$('#s2').show();
});
$('.b4').click(function() {
clearInterval(tI); <-stops the time
});
$('#r').click(function() {
tI = setInterval("setTimer()", 1000); <-not working, should continue the timer again
});
});
When the div #p is clicked it will start a game with a timer, this all works. Now if I click the div .b4 it will stop/pauze the timer, this also works. The problem is to start the timer again, continuing from where it was stopped.
I’ve tried tI = setInterval("setTimer()", 1000); when clicking the div #r but the problem with this is that is will start the timer, but it will not continue from the time it was stopped. It will continue, but from the time where it should be if it wasn’t stopped/pauzed.
SO how can I fix this? I want to pause the time (think I have this part right) and then continue it again when clicking #r
This is how my timer function is build:
function gameStart() {
setBlocks();
tM = $('#a1 div.tm');
hS = $('#a1 div.hs');
oT = new Date();
tI = setInterval("setTimer()", 1000);
setHs();
$('.ht').click(hint);
$('.b3').click(reset);
}
//Set timer
function setTimer() {
var n = new Date();
tM.text(getTimeText(n.getTime() - oT.getTime()));
}
//Build timer
function getTimeText(v) {
var vH = Math.floor(v / 3600000);
var vM = Math.floor((v - (vH * 3600000)) / 60000);
var vS = Math.floor((v - (vH * 3600000) - (vM * 60000)) / 1000);
return set2Digit(vH) + ':' + set2Digit(vM) + ':' + set2Digit(vS);
}
function set2Digit(ov) {
var os = '0' + ov;
return os.substr(os.length - 2, 2);
}
–EDIT–
With this html I get the time to show: <div class="tm">00:00:00</div>
–EDIT2–
Okay created a new function. It grabs the paused time, so from this point the time should continue:
$('#r').click(function() {
$('#s1').hide();
tI = setInterval("continueTimer()", 1000); //NEW
$('#s2').show();
});
//Test
function continueTimer() {
divObj = document.getElementById("tm");
tM.text(divObj.innerText);
}
At the moment, the time pauses but doesn’t continue when this function is fired… So how do I start the timer from this point? I think I am close
It is because in
setTimermethod you are creating anew Dateobject. So everytime this method executes it will take the current time. If you want to continue form where the timer was stopped instead of creatingnew Dateobject everytime, maintain the start date when the timer starts in a variable and then use that variable insidesetTimermethod.Modify the below method and add a global variable.