我们做活动页面有时候需要做当日倒计时,或者倒计时10s,下面是代码:
html
<div class="time">距今日活动结束:<span id="time"></span></div>
js
function NextTime(next, cb) {
var t;
(function ft(){
var dif = (next.getTime() - (new Date()).getTime()) / 1000;
if(dif > 0){
t = setTimeout(ft, 1000);
if(cb)
cb(Math.floor(dif % 86400 / 3600), Math.floor(dif % 3600 / 60), Math.floor(dif % 60));
} else {
clearTimeout(t);
}
})();
return function(){
clearTimeout(t);
};
}
function lpad(num, n) {
var len = num.toString().length;
while(len < n) {
num = "0" + num;
len++;
}
return num;
}
var now = new Date();
var next = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
new NextTime(next, function(hour, minute, second){
document.getElementById("time").innerHTML=lpad(hour, 2) + ':' + lpad(minute, 2) + ':' + lpad(second, 2);
});
倒计时10s
var next = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
改成
var next = new Date(now.getFullYear(), now.getMonth(), now.getDate(),now.getHours(),now.getMinutes(),now.getSeconds()+10);