记录一下书写setTimeout模拟setInterval的思路
思路
需要的功能:
- 可以间隔调用某个函数,且可以传递参数
- 函数可以在达到某个条件的时候停止执行,即将定时器清除
- 可以手动清除定时器
实现
-
根据功能确定入参
fn: Function 要间隔调用的函数 time: Number 间隔调用时间 endC: Function 结束条件 -
函数书写
function myInterval(fn,time = 1000,endC){ let timer return { clearTimer(){ if(timer) clearTimeout(timer) }, setTimer(){ if(timer) this.clearTimer() if(endC && typeof endC === 'function') { if(endC(...arguments)) return false //如果达到终止条件,跳出函数 } timer = setTimeout(()=>{ fn.apply(this,arguments) //间隔调用函数 this.setTimer.apply(this,arguments) },time) } } }
测试
let op ={count:0}
function test(op){
op.count++
console.log(op.count)
}
let t = myInterval(test,1000,(op)=>{return op.count >= 5})
t.setTimer(op);
结果
```