我将提出一种完全不同的倒计时方法;带有回调的生成器。一开始你可能会想,我为什么要这样做?但是使用生成器可以为您节省大量重复使用的代码。我还使用window.setTimeout
了 This 来确保如果您的回调执行时间比您的时间间隔长,您不会发生令人讨厌的事情。
代码中的注释应该可以帮助您了解正在发生的事情。
// 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);