模拟setinterval

setInterval弊端很多,具体区别大致在这里说下:

1)根据事件循环机制,setInterval是等待 call stack为空的时候才会执行回调(ps:只是将定时器代码添加到消息队列,而不是何时执行代码),另外setInterval本身给定的回调函数执行的时间 比 设定的时间间隔长,也会有问题。
2)某些间隔会被跳过,无视网络延迟、调用方法报错扔会继续执行
3)每个setTimeout产生的任务会直接push到任务队列中,而setInterval在每次 将任务push到队列前,都要进去一次判断(上次任务是否在队列中)

从而使用setTimeout模拟setInterval,代码如下

  class timer {
        timelist = []
        addTimer(name,callback,time = 2000){
          this.timelist.push({
            name,
            callback,
            time
          })
          this.runTimer(name)
        }
        runTimer(name){
          const _this = this;
          (function inner() {
              const task = _this.timelist.find(item =>{
                return item.name == name
              })
              if(!task) return //没找到return
              task.t = setTimeout(()=>{
                task.callback()
                clearTimeout(task.t)
                inner()
              },task.time) 
          })();
        }
        clearTimer(name){
          const index = this.timelist.findIndex(item => item.name == name)
          if(index != -1){
            clearTimeout(this.timelist[index].t)
            this.timelist.splice(index,1)
          }
        }
      }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值