vue中使用setInterval#

 

Copy

this.chatTimer = setInterval(() => { console.log(this.chatTimer); this.chatMsg(); }, 1000);

然后再组件销毁前进行清除

 

Copy

beforeDestroy() { clearInterval(this.chatTimer); this.chatTimer = null; }

根据 setInterval 返回的 id 打印来看,请除定时器并没有成功

但是这样不行,定时器在局部更新的时候会多次赋值.更改了一种写法,加了一重判断之后依旧无法解决.

 

Copy

if (!this.chatTimer) { this.chatTimer = setInterval(() => { console.log(this.chatTimer); this.chatMsg(); }, 1000); }

解决#

使用全局变量

 

Copy

window.chatTimer = setInterval(() => { console.log(window.chatTimer); this.chatMsg(); }, 1000);

 

Copy

destroyed() { clearInterval(window.liaotianTimer); },

最终解决#

 

Copy

const chatTimer = setInterval(() => { console.log(chatTimer); this.chatMsg(); }, 1000); this.$once('hook:beforeDestroy', () => { clearInterval(chatTimer); })

分类: Vue

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐