Vue定时器轮询 及 销毁定时器

1,942 阅读1分钟

项目中我们经常需要实现轮询 每隔几秒请求一次接口刷新数据 一般都会使用setInterval,但要注意单纯使用它可能导致页面卡死 原因是setInterval不会清除定时器队列,每重复执行1次都会导致定时器叠加,卡死。 但是setTimeout是自带清除定时器的 所以可以叠加使用

window.setInterval(() => {
  setTimeout(fun, 0)
}, 1000)

在需要结束轮询,或者beforeDestroy生命周期函数中 销毁定时器

clearInterval(this.timer)

具体实例

data: function () {
      return {
            timer: '',
		}
	}
	
methods: {
	compute () {
		this.timer = window.setInterval(() => {
	                  setTimeout(this.pollingFunc(), 0)
	                }, 1000)
	},
	pollingFunc () {
	          console.log('poll')
	          this.$http
	            .get(api.MoSum, {
	              params: { 'data_type': 2, 'task_id': this.task_id }
	            })
	            .then(res => {
	              console.log(res.result.data)
	              if (res.status === 200) {
	                this.tableData = res.result.data
	                this.loading = false
	                clearInterval(this.timer)
	              }
	            })
	        }
}