分享一个超好用的 轮询 + 定时器管理器

 

定时器和轮询都是前端小伙伴使用得比较频繁的功能,重复封装、改动都会浪费大量时间,不妨使用下面的一个实战骨架,  再进行自己个性化封装, 实现自己一劳永逸的定时和轮询。

// 定时器管理
class timerManage {
  constructor() {}
  // 设置定时器, 有timerKey, 则做去重处理
  set(timerKey, timerId) {
    if (this[timerKey]) {
      this.clearTimer(timerKey);
    }
    this[timerKey] = timerId;
  }
  // 获取定时器id
  get(timerKey) {
    return this[timerKey];
  }
  // 获取当前实例
  getAllTimer() {
    return this;
  }
  // 清除定时器
  clearTimer(timerKey) {
    clearInterval(this[timerKey]);
    delete this[timerKey];
  }
  // 清除所有定时器
  clearAllTimer() {
    Object.keys(this).forEach((item) => {
      clearInterval(this[item]);
      delete this[item];
    });
  }
}

// 创建定时器管理实例
const timerMg = new timerManage();

// 默认执行函数
const default_todoSomeThingFn = () => {
  console.log("执行默认函数完毕!");
  setTimeout(()=>console.log(Object.keys(timerMg.getAllTimer())))
  return true;
};

// 轮询体
const roundQueryFn = (
  todoSomeThingFn = default_todoSomeThingFn,
  timerKey = ""
) => {
  // 创建定时器
  let timer = setInterval(todoFn, 100);
  // 有传 timerKey
  timerKey ? timerMg.set(timerKey, timer) : timerMg.set(timer, timer);
  // 执行体
  todoFn();
  function todoFn() {
    console.log(Object.keys(timerMg.getAllTimer()));
    // 返回 ture 则 执行内容完毕, 结束轮询
    const result = todoSomeThingFn();
    if (result) {
      timerKey ? timerMg.clearTimer(timerKey) : timerMg.clearTimer(timer);
    }
  }
};

module.exports = {
  roundQueryFn,
};
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值