vue中重复设置定时器导致时间加速
最近在项目中使用setInterval()时候,发现多次创建定时器setInterval,会导致时间加速,最后发现是因为定时器清除的写法有问题,正确的写法需要使用 if 判断清除,直接在代码前调用clearInterval是会出问题的。
正确代码如下:
if (state.countTimer) { // 判断清除
clearInterval(state.countTimer)
}
state.countTimer = setInterval(() => {
// 创建定时器
if (state.pageData.time === 0) {
// 清除定时器
clearInterval(state.countTimer)
state.countTimer = null
state.timeDay = '00'
state.timeHour = '00'
state.timeMinute = '00'
state.timeSecond = '00'
} else {
state.pageData.time--
countdown()
}
}, 1000)