vue轮询方法

// 页面挂载完成后运行轮询
mounted() {
    this.timer = window.setInterval(()=>{
        setTimeout(()=>{
	        // 轮询里的处理代码
		    this.getOrderLists();
	    },0);
    },10000);
},
methods: {
    getOrderLists() {
        //请求接口
    }
},
// 页面销毁的时候清除定时器
destroyed() {
  	window.clearInterval(this.timer);
}

1.注意问题:
一般轮询都会使用setInterval,但是单独使用它会使页面卡死。

2.使用说明:
setInterval不会清除定时器队列,每重复执行1次都会导致定时器叠加,会出现网页卡死现象。但是setTimeout是自带清除定时器的,两者结合使用将避免页面卡死。

页面初始化,待开始轮询后,离开页面,通过生命周期destroyed钩子函数,销毁定时任务。

猜你喜欢

转载自blog.csdn.net/bo_ranlove/article/details/129990667