倒计时代码(兼容ios)
beforeDestroy(){ //页面销毁前清除定时器
clearInterval(this.countTimes)
}
methods:{
timer(){
let u = navigator.userAgent;
if(!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)){ //ios端
let iosPreTime=this.predate.split(/[- :]/) //ios端与安卓端时间格式不同,需做兼容处理
let preTime = new Date(iosPreTime[0],iosPreTime[1]-1,iosPreTime[2],iosPreTime[3],iosPreTime[4],iosPreTime[5]).getTime()
this.countTimes=setInterval(()=>{
let nowTime = new Date().getTime();
let obj = null;
if(preTime - nowTime > 0){
let time = (preTime - nowTime) / 1000;
let day = parseInt(time / (60 * 60 * 24));
let hou = parseInt(time % (60 * 60 * 24) / 3600);
let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
obj = {
day: day<10?'0'+day:day,
hou: hou<10?'0'+hou:hou,
min: min<10?'0'+min:min,
sec: sec<10?'0'+sec:sec
};
this.timing = obj.day + '天' + obj.hou + '时' + obj.min + '分' + obj.sec + '秒';
} else {
obj = {day:'00',hou:'00',min:'00',sec:'00'};
clearInterval(this.countTimes)
}
},1000)
}else{ //非ios端 --- 安卓端,pc端
let preTime = new Date(this.predate).getTime() //注意后端接口返回的predate格式应为 2020-02-02 20:20:20
this.countTimes=setInterval(()=>{
let nowTime = new Date().getTime();
let obj = null;
if(preTime - nowTime > 0){
let time = (preTime - nowTime) / 1000;
let day = parseInt(time / (60 * 60 * 24));
let hou = parseInt(time % (60 * 60 * 24) / 3600);
let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
obj = {
day: day<10?'0'+day:day,
hou: hou<10?'0'+hou:hou,
min: min<10?'0'+min:min,
sec: sec<10?'0'+sec:sec
};
this.timing= obj.day + '天' + obj.hou + '时' + obj.min + '分' + obj.sec + '秒';
} else {
obj = {day:'00',hou:'00',min:'00',sec:'00'};
clearInterval(this.countTimes)
}
},1000)
}
},
}
一般页面的定时器的使用及清除
setInterval定时器:请保证在页面销毁前清除该定时器,如在beforeDestroy生命周期里清除定时器
setTimeout定时器:该定时器只使用一次,为避免占用内存,请使用后即清除
如let times=setTimeout(()=>{
console.log("定时器触发了")
clearTimeout(times) //执行完相关语句后即可清除定时器
})
使用了keepAlive的页面的定时器的使用及清除
因为keepAlive的机制,再次进入缓存页面,生命周期会发生改变(见https://www.cnblogs.com/huihuihero/p/11905439.html),created及mounted生命周期将不再执行。数据不会更新。
若定时器触发放在了created或mounted生命周期里。则再次进入keepAlive页面,因created及mounted生命周期不再执行,定时器也将不再执行。
若想在每次进入keepAlive的页面依旧触发定时器,以及离开此页面清除定时器。则:
定时器触发放在activated生命周期里,定时器清除放在deactivated生命周期里即可。
如
activated(){
this.times=setInterval(()=>{
console.log("定时器触发了")
})
}
deactivated(){
clearInterval(this.times)
}
原文地址:https://www.cnblogs.com/huihuihero/p/12195643.html
时间: 2024-10-18 19:42:01