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() {
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();
}
});
Could somebody give me some advice how to handle this?
You’re continuously setting timeouts in your
whileloop. Just set one timeout instartand set timeouts in thetickfunction (you need to setselftothis):