利用setTimeout实现setInterval

这里采用构造函数的方式

function SetTime(){
    this.hook =true
}
SetTime.prototype.setIntervals = function(fn,time){
    if(this.hook){
        setTimeout(()=>{
            fn()
            this.setIntervals(fn,time)
        },time)
    }
}
SetTime.prototype.stopInterval = function(){
    this.hook = false
}

let time = 0
let interval = new SetTime()

interval.setIntervals(function(){
    console.log(time)
    if(time>=10){
        interval.stopInterval()
    }
    time++
},100)

 

posted @ 2021-01-12 16:56  JS-Feng  阅读(468)  评论(0编辑  收藏  举报