其他分享
首页 > 其他分享> > 利用setTimeout实现setInterval

利用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)

 

标签:function,hook,setInterval,interval,利用,SetTime,time,setTimeout,fn
来源: https://www.cnblogs.com/styleFeng/p/14267858.html