setTimeout 实现 setInterval

原理:定义一个自循环的函数,并用setTimeout启动
实现:

let mySetInterval = function(f, wait){
    let interval = function(){
        setTimeout(interval, wait)
        f()
    }
    setTimeout(interval, wait)
}

优化:可控制循环次数,并能合理抛出错误

let mySetInterval = function(f, wait, count){
    let interval = function(){
        if(typeof count === "undefined" || count-- > 0){//保证不传入参数 count 也可以运行
            setTimeout(interval, wait)
            try{
                f()
            } catch(e){
                count = 0;
                throw e.toString();
            }            
        }
    }
    setTimeout(interval, wait)
}
Comments
Write a Comment