前言
直接使用
while (!this.end) {
await new Promise((resolve) => setTimeout(resolve, 5000))
await this.getData()
}
beforeDestroy() {
this.end = true
},
封装
let timeWorker = {};
export const myInterver = (fn, time = 0) => {
let timeCount = Math.random();
var key = Symbol('timer');
timeWorker[key] = true;
const start = async () => {
do {
console.log('自定义延时器启动', timeCount);
await fn();
await new Promise((resolve) => setTimeout(resolve, time));
} while (timeWorker[key]);
};
start();
const clear = () => {
timeWorker[key] = false;
console.log('自定义延时器关闭', timeCount);
};
return { clear };
};
使用
this.timer = myInterver(this.getDeviceData, 5000);
beforeDestroy() {
this.timer.clear();
},