1.注意点
小程序中定时器在页面切换时候并不会中断,后台会持续叠加请求,因此在页面销毁和隐藏时候需要中断循环,此处通过设置一个全局的标志位来处理
2.代码
data: { timerContinue: true }, // 点击左上角返回时候触发 onUnload: function () { this.data.timerContinue = false }, // 按系统home键返回时候触发 onHide: function () { this.data.timerContinue = false }, onShow: function () { this.data.timerContinue = true // 如果在tab对应的页面中,每次进入需要重新启动循环 this.updateEndTime(23,59,59) }, updateEndTime: function (_hour, _minute, _second) { //当前时间,距1970年1月1日的秒数 //通过返回的小时及分钟生成对应的日期对象 var now = new Date() var end = new Date() end.setHours(_hour) end.setMinutes(_minute) end.setSeconds(_second) // 转化为毫秒,计算差值 var now_millisecond = now.getTime() var end_millisecond = end.getTime() var diff = (end_millisecond - now_millisecond) / 1000 // 秒数转化为小时,分,秒 var hour = Math.floor(diff / 3600) hour = hour >= 10 ? hour : '0' + hour diff = diff % 3600 var minute = Math.floor(diff / 60) minute = minute >= 10 ? minute : '0' + minute diff = diff % 60 var second = diff second = second >= 10 ? second : '0' + second var countDown = hour+':'+minute+':'+second console.log(countDown) // 循环调用 if (this.data.timerContinue) { setTimeout(() => { this.updateEndTime(_hour, _minute, _second) }, 1000) } },