2011-09-06 13 views
0

我在頁面上有很多倒計時定時器。定時器倒計時從當前時間到今後的剩餘時間。單頁上的很多定時器

我需要從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

您不斷在您的while循環中設置超時。只需設置一個超時的start,並在tick功能設置超時(需要設置selfthis):

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); 
    } 
}; 
+2

+1徹底/周到的答案,不錯的一個。另外,也可以考慮使用setInterval來實現這種功能。 – Timbo

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); 
}; 
+0

我應該命名我的靜態變量startTime或pageLoadedTime而不是currTime。可能它會使我的代碼更具可讀性。更正了我的代碼。 – drupality