首页 > 代码库 > javascript 倒计时
javascript 倒计时
// 倒计时
var fnTimeCountDown = function (time) {
var time = new Date(time).getTime() - new Date().getTime(), // 倒计时时间转变为毫秒数
days, hours, min, sec, temp;
if (time <= 0) {
return null;
}
days = Math.floor(time / (24*3600*1000));
temp = time % (24*3600*1000); // 不够天的转换成小时
hours = Math.floor(temp / (3600*1000));
temp = temp % (3600*1000); // 剩余的分钟数
min = Math.floor(temp / (60*1000));
temp = temp % (60*1000);
sec = Math.floor(temp / (1000));
// 格式化:"05"
var zero = function (n) {
var n = parseInt(n, 10);
if (n > 0) {
if (n <= 9) {
n = "0" + n;
}
return n;
} else {
return "00";
}
};
return {
days: days,
hours: zero(hours),
min: zero(min),
sec: zero(sec)
};
};
var future = "2014/01/01 00:00",
countobj = null,
timer = null,
countdown = function (time, callback) {
// 倒计时数据对象:countobj
countobj = fnTimeCountDown(time);
callback && callback(countobj);
if (countobj) {
timer = setTimeout(function () {
countdown(time, callback);
}, 1000);
} else {
// 倒计时结束
clearTimeout(timer);
}
};
setTimeout(function () {
countdown(future, function (obj) {
if (obj) {
// 倒计时应用
console.log(obj);
} else {
// 倒计时结束
console.log("countdown over!");
}
});
}, 0);
javascript 倒计时