js代码实现
let [timer, hours, minutes, seconds, msec] = [null, 0, 0, 0, 0]
// 主函数,开始倒计时
function startCountdown(start, end) {
clearInterval(timer)
start = start.replace(/-/g, '/')
let dateDiff = new Date(start).getTime() - end.getTime()
timer = setInterval(function() {
if (dateDiff >= 100) {
dateDiff -= 100
handleTimeout(dateDiff)
} else {
// 倒计时结束,刷新页面
window.location.reload()
clearInterval(timer)
}
}, 100
}
// 相差时间计算时分秒
function handleTimeout(dateDiff) {
// 计算出相差天数
let dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000))
let leave1 = dateDiff % (24 * 3600 * 1000)
// 计算出小时数
hours = Math.floor(leave1 / (3600 * 1000))
let leave2 = leave1 % (3600 * 1000)
//计算相差分钟数
minutes = Math.floor(leave2 / (60 * 1000))
let leave3 = leave2 % (60 * 1000)
//计算相差秒数
seconds = Math.floor(leave3 / 1000)
let leave4 = leave3 % 1000
// 计算0.1秒
msec = Math.floor(leave4 / 100)
},
格式(以下是ES6语法)
- 倒计时格式:天:时:分:秒:0.1秒
${dayDiff}:${hours}:${minutes}: ${seconds} :${msec}
- 倒计时格式:时:分:秒:0.1秒
${hours + dayDiff * 24}:${minutes}: ${seconds} :${msec}
实现效果
有问题私信我哈,我会第一时间回你哒