手写实现setInterval

542 阅读1分钟

用setTimeout实现setInterval

setInterval不会停止,作为改进,在手写时传入count参数,对setInterval执行次数进行限制

function mySetInterval(fn,timeout,count){
    function interval(){
        if(count > 0){
            setTimeout(interval,timeout)
            fn()
            count--
            //setTimeout(interval,timeout)

        }
    }
    setTimeout(interval,timeout)
}
mySetInterval(()=>{
    console.log(1)
},1000,3)

将setTimeout放在fn()和count--的上面也可以,因为setTimeout是异步任务。