今天在作一个定时任务轮询时,使用按钮开启轮询任务,再次点击按钮设置关闭轮询任务,发现轮询不能被正常关闭,代码如下:
methods:{
switchChange(val) {
if (val) {
this.time = window.setInterval(()=>{
console.log("轮询");//被轮询任务
},2000)
} else {
console.log("结束轮询");
window.clearInterval(this.time);
}
}
}
后面将代码改成如下,就可以了
methods:{
getDateLoop() {
this.time = setInterval(()=>{
console.log("轮询");
},2000)
},
switchChange(val) {
if (val) {
this.getDateLoop();
} else {
console.log("结束轮询");
window.clearInterval(this.time);
}
}
}