countdown() {
// 做判断当倒计时结束时都为0
if (new Date().getTime() >= this.endTime) {
this.d = '00'
this.h = '00'
this.m = '00'
this.s = '00'
return
}
// 用结束时间减去当前时间获得倒计时时间戳
const msec = this.endTime - new Date().getTime()
const d = parseInt(msec / 1000 / 60 / 60 / 24) // 算出天数
const h = parseInt(msec / 1000 / 60 / 60 % 24)// 算出小时数
const m = parseInt(msec / 1000 / 60 % 60)// 算出分钟数
const s = parseInt(msec / 1000 % 60)// 算出秒数
// 给数据赋值
this.d = d
this.h = h > 9 ? h : '0' + h
this.m = m > 9 ? m : '0' + m
this.s = s > 9 ? s : '0' + s
// 定义this指向
const that = this
// 使用定时器 然后使用递归 让每一次函数能调用自己达到倒计时效果
setTimeout(function() {
that.countdown()
console.log('aaaa')
}, 1000)
},
vue定时计时
最新推荐文章于 2024-08-27 16:08:12 发布
这篇博客详细介绍了如何使用JavaScript编写一个倒计时功能。通过计算结束时间与当前时间的差值,动态更新天数、小时数、分钟数和秒数。在每一秒过去后,函数递归调用自身以实现连续的倒计时显示。
1436

被折叠的 条评论
为什么被折叠?



