I have a javascript timer that is not working correctly. When I insert it into my browser the seconds are jumping back slightly. I believe it might be something to do with the milliseconds not being converted correctly in seconds/minutes/hours but I'm not sure. Here is my code:
var link = userLink + '/games/' + $scope.currentGame;
ref.child(link).once('value', function(snapshot) {
var game = snapshot.val();
var startTime = Date.parse(game.started);
var timeNow = Date.now();
var timeLapsed = (timeNow - startTime);
var mydate = new Date(timeLapsed);
var humandate = mydate.getUTCHours()+ " hours, " + mydate.getUTCMinutes()+ " minutes and " + mydate.getUTCSeconds()+ " second(s)";
console.log(humandate);
console.log( mydate.getUTCHours())
var timeVar = document.getElementById('timer'), seconds = mydate.getUTCSeconds(), minutes = mydate.getUTCMinutes(), hours = mydate.getUTCHours(), time;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
timeVar.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") +
":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") +
":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
var time = setTimeout(add, 1000);
}
timer();
});
The initial starting time is grabbed from a firebase database for persistence (the timer is intended as part of game) and then the following functions increment the time. Any help would be appreciated. Thanks.