で感謝の方法は、それは非常に難しい2のタイマーを組み込むことができます。代わりに、再利用可能なオブジェクトコンストラクタを使用するだけです。 Demo here。
function Countdown(element, time) {
this.element = element;
this.time = time;
}
Countdown.time = function() {
return new Date().getTime()/1000;
};
Countdown.formatRemaining = function(timeRemaining) {
function fillZero(n) {
return n < 10 ? '0' + n : n.toString();
}
var days = timeRemaining/60/60/24 | 0;
var hours = timeRemaining/60/60 | 0;
var minutes = timeRemaining/60 | 0;
var seconds = timeRemaining | 0;
hours %= 24;
minutes %= 60;
seconds %= 60;
return days + ' day' + (days === 1 ? '' : 's') + ' ' + fillZero(hours) + ':' + fillZero(minutes) + ':' + fillZero(seconds);
};
Countdown.prototype.update = function() {
var timeRemaining = this.time + this.start - Countdown.time();
if(timeRemaining > 0) {
this.element.innerHTML = Countdown.formatRemaining(timeRemaining);
} else {
this.element.innerHTML = "Time's up!";
if(this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
};
Countdown.prototype.start = function() {
var countdown = this;
this.start = Countdown.time();
this.timer = setInterval(function() {
countdown.update();
}, 1000);
this.update();
};
jsFiddleが自動的に 'onload'ハンドラにラップするため、動作しないのが原因です。 – Ryan
ここにjsFiddleの問題が修正されています:http://jsfiddle.net/minitech/s7x2d/2/ – Ryan
jsFiddleの問題をソートしてくれてありがとう。実際に2つのインスタンスを実際に作成する方法はありません – user866190