一定要清楚定时器,,减少内存泄露
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;
}