This a question that has been revolving in my head and today I had this idea to fix it, but it didn't work. What I basically want is to be able to pause and resume a timer, and when I resume it, it should continue in the time that I left it, for example: I stop it in the middle of the second it was in so when I resume it, half a second later it goes to the next second. This is my code.
$(document).ready(function() {
a = new Timer("#timerText");
a.set(12, 1);
a.run();
});
function Timer(element) {
var minutes, seconds, finalTimeInSeconds, displayMinutes, displaySeconds, interval = 1000, self = this, timeLeftToNextSecond = 1000;
this.set = function(inputMinutes, inputSeconds) {
finalTimeInSeconds = inputMinutes * 60 + inputSeconds;
minutes = (Math.floor(finalTimeInSeconds / 60));
seconds = finalTimeInSeconds % 60;
this.print();
}
this.add = function(inputMinutes, inputSeconds) {
finalTimeInSeconds += inputMinutes * 60 + inputSeconds;
finalTimeInSeconds = (finalTimeInSeconds < 0) ? 0 : finalTimeInSeconds;
minutes = (Math.floor(finalTimeInSeconds / 60));
seconds = finalTimeInSeconds % 60;
this.print();
}
this.subtract = function(inputMinutes, inputSeconds) {
finalTimeInSeconds -= inputMinutes * 60 + inputSeconds;
finalTimeInSeconds = (finalTimeInSeconds < 0) ? 0 : finalTimeInSeconds;
minutes = (Math.floor(finalTimeInSeconds / 60));
seconds = finalTimeInSeconds % 60;
this.print();
}
this.reset = function() {
this.set(0, 0);
}
this.print = function() {
displayMinutes = (minutes.toString().length == 1) ? "0" + minutes : minutes; //ternary operator: adds a zero to the beggining
displaySeconds = (seconds.toString().length == 1) ? "0" + seconds : seconds; //of the number if it has only one caracter.
$(element).text(displayMinutes + ":" + displaySeconds);
}
this.run = function() {
ac = setInterval(function() {
secondStarted = new Date;
self.subtract(0, 1);
interval = 1000;
}, interval);
}
this.stop = function() {
stopped = new Date;
interval = stopped - secondStarted;
clearInterval(ac);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="timerText">00:00</div>
It does not work. If I stop it and then resume it the interval
doesn't get back to 1000
after one cycle. Also, I don't think I subtracting the Dates
the right way, because when I print the interval
number the numbers look a little off. What am I doing wrong here?
Thanks if you answer.