核心:添加页面隐藏和进入监听事件(visibilitychange),分别获取服务器时间计算(防止手机改时间)
直接上代码!
data函数定义
data() {
return {
currentstatus:true,
fwqStartTime:'',//总用时开始跑的服务器时间戳
usetime: 0,//在当前页面的总用时
}
},
生命周期mounted添加事件监听事件
mounted() {
document.addEventListener("visibilitychange", ()=> {
let stuts = document.visibilityState
this.initTime(stuts)
});
},
methods里编写this.initTime()初始化方法
initTime(ztext) {
//data中定义currentstatus,定义这个值是为了防止多次触发方法
if(ztext=='hidden' && this.currentstatus==true){
this.currentstatus = false
// 页面离开时存储离开的时间,并且暂停两个定时器
// let timestamp = (Date.parse(new Date()))/1000;
let timestamp = this.fwqStartTime + this.usetime; // 进入页面时服务器时间戳加上总用时秒数得到当前离开页面时间戳
window.localStorage.setItem('LEAVE_ALLTIME', this.usetime)
window.localStorage.setItem('LEAVE_TIME', timestamp)
clearInterval(this.timer)
} else if(ztext=='visible' && this.currentstatus==false){
// console.log('进来了', );
this.currentstatus=true
let leaveTime = parseInt(window.localStorage.getItem('LEAVE_TIME')) //离开时候的时间戳
let oldAllTime = parseInt(window.localStorage.getItem('LEAVE_ALLTIME')) //离开时候的总时间(秒数)
let Nowtime = await this.getFWQTime() //获取再次进入当前进入的时间戳
let ms = Nowtime-leaveTime
let newAlltime = oldAllTime + ms
console.log('离开的秒数',ms,'总计时秒数',newAlltime);
this.usetime = newAlltime
this.startTime();//定时器继续走
}
},
//进入页面总用时秒数(一直跑的)
startTime() {
this.timeall = setInterval(() => {
this.usetime++;
console.log('总时间',this.usetime)
}, 1000)
},
// 获取服务器时间,并且返回秒级时间戳
getFWQTime() {
return new Promise(resolve => {
let time='';//通过接口获取当前时间
let nowTime = (Date.parse(new Date(time)))/1000;
resolve(nowTime)
})
},
总结:浏览器对定时器是真的坑,隐藏页面就睡眠进程,再次进入就继续,无法一直计时,项目要求不严,直接用浏览器返回的时间戳计算离开时间,合理的话还是要结合服务器时间计算,
提示:千万别隐藏页面的时候调用接口获取离开的服务器时间戳,每个浏览器杀进程的时间不一样,不一定会存储了