vue 中 clearTimeout 特愿、clearInterval 失效仲墨、無(wú)效果
作者:子長(zhǎng)
?? 一般需要在組件、頁(yè)面銷毀后需要清除設(shè)置的延時(shí)器揍障、計(jì)時(shí)器目养,就需要用到 clearTimeout() 或者 clearInterval() ,正常情況下一般都能銷毀毒嫡,如下:
data(){
return{
times: null,
}
},
mounted() {
this.times = setInterval(() => {
console.log('計(jì)時(shí)中...')
}, 1000)
}癌蚁,
beforeDestroy(){
clearInterval(this.times)
this.times = null
}
但有些時(shí)候計(jì)時(shí)器不能及時(shí)銷毀,如下:
let times
window.onresize = () => {
if(times!== null){
clearTimeout(times);
times= null
}
times= setTimeout(() => {
console.log('延時(shí)中...')
}, 1000);
}
??以上代碼邏輯不能及時(shí)清除計(jì)時(shí)器兜畸,需要通過 window.setTimeout 努释、window.clearTimeout 才能及時(shí)清除:
let times
window.onresize = () => {
if(times!== null){
window.sclearTimeout(times);
times= null
}
times= window.ssetTimeout(() => {
console.log('延時(shí)中...')
}, 1000);
}