Last time I talked about the disadvantages of these two timers, this time I will talk about simulating each other.

function mySetInterval(fn, t){
    let timer = null;
    function interval(){
        fn();
        timer = setTimeout(interval, t)
    }
    interval();
    return {
        clear: () = >{
            clearTimeout(timer)
        }
    }
}
let a = mySetInterval(() = >{
    console.log('xxx')},1000)
Copy the code

To be honest, I didn’t know what good it was to be asked. Because I don’t know about timers, I just know how to use them. Later, I studied the birth date of these two “goods”. I talked about that in the last post. I got kind of obsessed with it. Because I’ve learned that both of their flaws are set times, there are a lot of factors that can affect the timing of the callback. Now that we know the disadvantage of setInterval is that it may not repeat on time, may be executed continuously, and may skip a callback function. SetTimeout simulation must solve this problem, so two functions are realized. First, if there is a timer in the main thread, no new timer can be added. The second is to execute the callback function repeatedly for a specified amount of time. What advantage should be these two, there are other I also can’t think of, there will be brothers and sisters meng can give advice. Thank you.

Wouldn’t it be nice to do the simulation the other way around, just do a setInterval and clear it up? I understand that.

function mySetTimeout(fn, t){
    let timer = setInterval(() = >{
        fn();
        clearInterval(timer)
    },t)
}
let a = mySetTimeout(() = >{
    console.log('xxx')},1000)
Copy the code

This one doesn’t take into account the case of wearing.