vue项目使用定时器每隔几秒运行一次某方法
代码如下:
data() {
return {
timer:null, //定时器名称
};
},
created() {
this.setTime();
},
beforeDestroy() {
clearInterval(this.timer); // 清除定时器
this.timer = null;
},
methods: {
setTime(){
//每隔一分钟运行一次保存方法
this.timer = setInterval(()=>{
this.heartBeat();
},60000)
},
heartBeat(){
axios.post("/api/member/ueditor/heartBeat",{}).then(res=>{
if (res.code == '200') {
console.log(res.body.result);
}else{
console.log("心跳停止");
}
})
}
}
上面这样写已经实现功能,关闭页面不会继续执行。长时间运行页面也没有卡死。

浙公网安备 33010602011771号