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

 

上一篇:LeeCode( 模拟)57_插入区间


下一篇:【leetcode】-区间问题-57. Insert Interval