单页上有很多计时器

时间:2011-09-06 12:22:01

标签: javascript timer

页面上有很多倒数计时器。计时器倒计时将来的剩余时间从现在开始。

我需要将当前的计时器值与html分开,因为页面上的元素可能会更改(出现/消失)导致过滤/排序脚本。

我天真的实现只是挂掉了浏览器:

var CountdownTimer = function(id, endTime) {    
    this.id = id;
    this.endTime = endTime;
    this.remainingSeconds = parseInt((this.endTime - CountdownTimer.startTime) / 1000);
};
CountdownTimer.prototype.start = function() {
    while (this.remainingSeconds > 0) {
        setTimeout('this.tick()', 1000);
    }
};

CountdownTimer.prototype.tick = function() {
    this.remainingSeconds--;
    console.log(this.id + ': ' + this.remainingSeconds);
};

CountdownTimer.startTime = new Date().getTime();

$(document).ready(function() {  
    var endTimes = Drupal.settings.snuper_filter.end_times,
        activeTimers = [];

    for(var i = 0; i < endTimes.length; i++) {
        activeTimers.push(new CountdownTimer(endTimes[i].nid, endTimes[i].endTime));
    }
    endTimes = Drupal.settings.snuper_filter.end_times = null;

    for (var i = 0; i < activeTimers.length; i ++) {
        activeTimers[i].start();        
    }

});

有人可以给我一些建议吗?

2 个答案:

答案 0 :(得分:2)

您在while循环中不断设置超时。只需在start中设置一个超时,并在tick函数中设置超时(您需要将self设置为this):

CountdownTimer.prototype.start = function() {
    var self = this;
    setTimeout(function() {self.tick()}, 1000);
};

CountdownTimer.prototype.tick = function() {
    this.remainingSeconds--;
    console.log(this.id + ': ' + this.remainingSeconds);
    if(this.remainingSeconds > 0) {
        var self = this;
        setTimeout(function() {self.tick()}, 1000);
    }
};

答案 1 :(得分:0)

我不明白,你需要多少计时器,但下一段代码做了一些优化:

var CountdownTimer = function(id, endTime) {    
    this.id = id;
    this.endTime = endTime;
};

CountdownTimer.prototype.tickHandler=null;
CountdownTimer.prototype.start = function() {
  this.tickHandler=this.tick.bind(this);
  //or
  //var self=this;
  //this.tickHandler=function(){self.tick();};
  setTimeout(this.tickHandler, 1000);
};

CountdownTimer.prototype.tick = function() {
    var remainingSeconds=this.endTime-new Date().getTime();
    console.log(this.id + ': ' + remainingSeconds);
    if(remainingSeconds>0)setTimeout(this.tickHandler, 1000);
};