Trying to build a very simple Javascript countdown. However, whenever the tab is inactive, the countdown begins to lag and holds an incorrect count.
See jsfiddle here for example: https://jsfiddle.net/gbx4ftcn/
function initTimer(t) {
var self = this,
timerEl = document.querySelector('.timer'),
minutesGroupEl = timerEl.querySelector('.minutes-group'),
secondsGroupEl = timerEl.querySelector('.seconds-group'),
minutesGroup = {
firstNum: minutesGroupEl.querySelector('.first'),
secondNum: minutesGroupEl.querySelector('.second')
},
secondsGroup = {
firstNum: secondsGroupEl.querySelector('.first'),
secondNum: secondsGroupEl.querySelector('.second')
};
var time = {
min: t.split(':')[0],
sec: t.split(':')[1]
};
var timeNumbers;
function updateTimer() {
var timestr;
var date = new Date();
date.setHours(0);
date.setMinutes(time.min);
date.setSeconds(time.sec);
var newDate = new Date(date.valueOf() - 1000);
var temp = newDate.toTimeString().split(" ");
var tempsplit = temp[0].split(':');
time.min = tempsplit[1];
time.sec = tempsplit[2];
timestr = time.min + time.sec;
timeNumbers = timestr.split('');
updateTimerDisplay(timeNumbers);
if (timestr === '0000')
countdownFinished();
if (timestr != '0000')
setTimeout(updateTimer, 1000);
}
function animateNum(group, arrayValue) {
TweenMax.killTweensOf(group.querySelector('.number-grp-wrp'));
TweenMax.to(group.querySelector('.number-grp-wrp'), 1, {
y: -group.querySelector('.num-' + arrayValue).offsetTop
});
}
setTimeout(updateTimer, 1000);
}
I'm unsure whether the problem lies with the animation, or with the JS code itself.
For clarification: I want the countdown to continue when the tab is inactive, or to 'catch up with itself' when the tab comes back in to focus.
I know that setTimeout
and setInterval
can cause issues with inactive tabs, but I'm not entirely sure how to fix this.
Any help would be much appreciated!