Promise模拟延时器,在请求结束之后再进入等待

前言

  • 如果是要用settimeout模拟setInterval可以看这篇链接
  • 因为clearTimeout失效的问题,所以放弃用上面的方式

直接使用

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();//调试用
  // 定义一个key,来标识此定时器
  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();
  },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值