使用jQuery计时器在新选项卡上运行计时器

时间:2014-05-29 10:30:39

标签: javascript jquery wordpress timer

我正在使用此计时器插件https://github.com/jchavannes/jquery-timer,并尝试在用户打开新标签时保持计时器处于活动状态。我已经阅读了关于这个主题的几篇SO帖子(specifically this one),但我仍然有点迷失。

我试图使用以下代码

更新timer.js文件中的setTimer函数
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);

    };

但是这会为每个滴答生成一个控制台错误(在此过程中通过屋顶粉碎我的CPU!)

  

未捕获的TypeError:无法读取属性' getTime'未定义的

我觉得这很简单,我错过了。

1 个答案:

答案 0 :(得分:1)

您要使用的是requestAnimationFrame功能。

它的作用基本上是setTimeout(function,0)的作用,但是当您转到其他标签时,或者您运行代码的标签处于非活动状态时。

将此添加到您的代码中(它也可以跨浏览器友好):

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);
         };
})();

并以这种方式致电requestAnimFrame(<function you want to call>)

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);

参考文献:http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/