我會提出一種完全不同的倒數計時器的方法;帶回調的發電機。起初你可能會想,爲什麼我會這樣做?但是使用生成器可以爲重複使用的東西節省大量代碼。我也使用window.setTimeout
這是爲了確保您的回調花費的時間比您的間隔時間更長,確保您不會發生令人討厭的事情。
通過代碼的評論應該有助於你理解發生了什麼。
// createCountDown(Date end_time [, Function callback, Integer ms_interval])
// returns an Object properties: ms, ss, mm, hh, dd, MM, yy, timer (current)
// same Object is passed as parameter 1 to callback
function createCountDown(time, callback, ms) {
var future = time.valueOf(), // cache these to save re-calling them later
f_ms = time.getUTCMilliseconds(),
f_ss = time.getUTCSeconds(),
f_mm = time.getUTCMinutes(),
f_hh = time.getUTCHours(),
f_dd = time.getUTCDate(),
f_MM = time.getUTCMonth(),
f_yy = time.getUTCFullYear(),
o = {timer: null}; // an object to make life easier
var f = function() { // the function that will handle the setTimeout loops
var d = new Date(), // the current time of each loop
remain = future - d.valueOf(); // difference (in ms)
if (remain > 0) {
// Totals
o['total_ms'] = remain; // if you'll never need all these, you can
o['total_ss'] = remain/ 1000 | 0; // comment or cut them out
o['total_mm'] = remain/ 60000 | 0;
o['total_hh'] = remain/3600000 | 0;
o['total_dd'] = remain/86400000 | 0;
// Differences (via UTC)
o['ms'] = (1000 + f_ms - d.getUTCMilliseconds()) % 1000; // same
o['ss'] = ( 60 + f_ss - d.getUTCSeconds() ) % 60;
o['mm'] = ( 60 + f_ss - d.getUTCMinutes() ) % 60;
o['hh'] = ( 24 + f_hh - d.getUTCHours() ) % 24;
o['dd'] = ( f_dd - d.getUTCDate() ) ; // below
o['MM'] = ( 12 + f_MM - d.getUTCMonth() ) % 12;
o['yy'] = ( f_yy - d.getUTCFullYear() ) ;
if (o['dd'] < 0) { // fix for negative days
d.setUTCMonth(d.getUTCMonth() + 1);
d.setUTCDate(0); // using number of days in current month
o['dd'] + d.getUTCDate();
}
callback(o); // invoke your callback
o.timer = window.setTimeout(f, ms); // set up next loop
}
}
ms || ms === 0 || (ms = 200); // default ms if not set
callback || (callback = function() {}); // default empty fn
f(); // start off the whole looping
return o;
}
現在寫您的callback
,這是要短得多,因爲你已經有了長遠的東西的方式進行。 console.log
使說明性的目的很容易。
function updateWCTime(o) {
console.log(
o['total_dd'] + ' days ' +
o['hh'] + ' hours ' +
o['mm'] + ' minutes ' +
o['ss'] + ' seconds'
);
}
最後,啓動它。
createCountDown(new Date("April 27, 2013 09:00:00"), updateWCTime);
啊,謝謝你打破了! Niels發現了這個問題,但我很高興你解釋了它背後的推理。 – Marlon 2013-04-21 13:05:59
我將自己的評論改爲了答案,因爲其中的解釋實際上不僅僅是評論的答案。 – jfriend00 2013-04-21 13:09:29