function countTime() {
let endDateDefault = '2021-04-17 10:59:59';
const date = new Date();
const now = date.getTime();
const endDate = new Date(endDateDefault);//设置截止时间
const end = endDate.getTime();
const leftTime = end - now; //时间差
let d, h, m, s, ms;
if (leftTime >= 0) {
// 天
d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
// 小时
h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
// 分钟
m = Math.floor(leftTime / 1000 / 60 % 60);
// 秒
s = Math.floor(leftTime / 1000 % 60);
// 毫秒
ms = Math.floor(leftTime % 1000);
ms = ms < 100 ? "0" + ms : ms;
s = s < 10 ? "0" + s : s;
m = m < 10 ? "0" + m : m;
h = h < 10 ? "0" + h : h;
console.log('倒计时:'+d+' '+h+':'+m+":"+s+":"+ms);
} else {
console.log('已截止');
clearInterval(clearTime);
}
}
//递归每秒调用countTime方法,显示动态时间效果
const clearTime = setInterval(countTime, 50);