I am using this timer plugin https://github.com/jchavannes/jquery-timer and am trying to keep the timer active when a user opens a new tab. I have read a couple of SO posts on this subject (specifically this one), but am still a bit lost.
I have attempted to update the setTimer function within the timer.js file with the following code
this.setTimer = function(time) {
var timer = this;
if(typeof this.action != 'function') {return;}
if(isNaN(time)) {time = this.intervalTime;}
this.remaining = time;
this.last = new Date();
this.broswerDelay = new Date();
this.increment = (1000 / 30);
this.clearTimer();
setInterval(function() {
this.now = new Date();
this.elapsedTime = (this.now.getTime() - this.broswerDelay.getTime());
if(this.elapsedTime > this.increment)
//Recover the motion lost while inactive.
time = Math.floor(this.elapsedTime/this.increment);
this.before = new Date();
}, this.increment);
this.timeoutObject = window.setTimeout(function() {timer.go();}, time);
};
But this generates a console error for each tick (smashing my CPU through the roof in the process!)
Uncaught TypeError: Cannot read property ‘getTime’ of undefined
I feel like this is something simple that I am missing.
What you want to use is the
requestAnimationFrame
function.What it does is basically what
setTimeout(function,0)
does, but when you go to a different tab, or whenever the tab where you’re running the code is not active.Add this to your code (it’s also cross browser friendly) :
and call
requestAnimFrame(<function you want to call>)
in this manner :References : http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/