Keep timer running on new tab with jQuery timer

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

Read More
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.

Related posts

Leave a Reply

1 comment

  1. 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) :

    window.requestAnimFrame = (function() {
      return window.requestAnimationFrame ||
             window.webkitRequestAnimationFrame ||
             window.mozRequestAnimationFrame ||
             window.oRequestAnimationFrame ||
             window.msRequestAnimationFrame ||
             function(/* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
               window.setTimeout(callback, 1000/60);
             };
    })();
    

    and call requestAnimFrame(<function you want to call>) in this manner :

    var prev=Date.now();
    var functionYouWantToRunOnLoop = function(){
      var current = Date.now();
      var elapsed = current - prev; //time difference between 2 function calls
      prev = current;
    
      //stuff you want to do while using the value of elapsed for computations
    
      requestAnimFrame(functionYouWantToRunOnLoop);
    }
    
    requestAnimFrame(functionYouWantToRunOnLoop);
    

    References : http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/