Many timers on single page
I have many countdown timers on the page. Timers countdown remaining time from current time to time in future.
I need to have current timer value seperate from html, because element on page may change (appear/disappear) cause filtering/sorting scripts.
My naive implementation just hangs out the browser:
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() {
t开发者_Python百科his.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();
}
});
Could somebody give me some advice how to handle this?
You're continuously setting timeouts in your while
loop. Just set one timeout in start
and set timeouts in the tick
function (you need to set self
to 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);
}
};
I don't understand, what you need many timers, but next code made some optimization:
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);
};
精彩评论