原方案-缺点
- 它需要在这个组件实例中保存这个
timer,如果可以的话最好只有生命周期钩子可以访问到它。这并不算严重的问题,但是它可以被视为杂物。 我们的建立代码独立于我们的清理代码,这使得我们比较难于程序化的清理我们建立的所有东西。 ```javascript data() {
return {timer: null // 定时器名称
}
},this.timer = setInterval(() => { // 某些操作 }, 1000)
beforeDestroy() {
clearInterval(this.timer);
this.timer = null;
}
<a name="YfSoT"></a>### 优化该方法是通过$once这个事件侦听器器在定义完定时器之后的位置来清除定时器```javascriptexport default {mounted() {const timer = setInterval(() => { ... }, 1000);this.$once('hook:beforeDestroy', () => clearInterval(timer);)}};
应用场景
请求轮询
timeRecorder() {let t = null;let that = this;t = setTimeout(time, 1000); //開始运行function time() {clearTimeout(t); //清除定时器that.time = moment().format("HH:mm");console.log(that.time,'一分钟一刷新')t = setTimeout(time, 1000 * 60); //设定定时器,循环运行}this.$once('hook:beforeDestroy', () => clearTimeout(t))}
定时刷新-每日
timeRecorder() {let t = null;let that = this;t = setTimeout(time, 1000); //開始运行function time() {clearTimeout(t); //清除定时器that.time = moment().format("HH:mm:ss");// console.log(moment().format("HH:mm:ss"),'一秒一刷新, 24点重新请求')if (that.time === '24:00:00') {that.fetchList()}t = setTimeout(time, 1000); //设定定时器,循环运行}this.$once('hook:beforeDestroy', () => clearTimeout(t))},
