一定要清楚定时器,,减少内存泄露
HTML渲染:
{{hangTime.day}} 天 {{hangTime.hour}} 时 {{hangTime.min}} 分 {{hangTime.second}} 秒
data(){
return{
timer:null,
}
//在需要的地方调用countTime,如获取到时间差的时候
countTime(time) {
let _this = this;
if (!this.timer) {
let leftTime = time
this.timer = setInterval(() => {
let isOver = true
let item = this.hangTime
if (Number(item.hour) === 0 && Number(item.day) === 0 && Number(item.min) === 0 && Number(
item
.second) === 0) {} else {
isOver = false
if (leftTime > 0) {
leftTime--;
// 天
this.hangTime.day = Math.floor(leftTime / 60 / 60 / 24)
// 时
let h = Math.floor(leftTime / 60 / 60 % 24)
this.hangTime.hour = h < 10 ? '0' + h : h
// 分
let m = Math.floor(leftTime / 60 % 60)
this.hangTime.min = m < 10 ? '0' + m : m
// 秒
let s = Math.floor(leftTime % 60)
this.hangTime.second = s
} else {
clearInterval(this.timer);
this.timer = null;
this.hangTime.day = '00'
this.hangTime.hour = '00'
this.hangTime.min = '00'
this.hangTime.second = '00'
}
}
if (isOver) {
clearInterval(this.timer);
this.timer = null;
}
}, 1000);
}
},
//一定要清楚定时器,,减少内存泄露
destroyed() {
clearInterval(this.timer)
this.timer = null;
}
该博客主要介绍了如何在Vue.js应用中实现一个实时倒计时功能,通过设置定时器更新HTML渲染。文章强调了正确清理定时器以防止内存泄露的重要性,并提供了具体的代码示例来展示如何在组件销毁时清除定时器。
4217

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



