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)
}
}
}