setTimeout 模拟 setInterval

2021-03-22  本文已影响0人  McDu

写一个 mySetInterVal(fn, a, b),每次间隔 a,a+b,a+2b,...,a+nb 的时间,然后写一个 myClear,停止上面的 mySetInterVal

function mySetInterval(fn, a, b) {
    let timer = null, count = 0;

    const start = () => {

        timer = setTimeout(() => {
            fn()
            count++
            start()
        }, a + count++ * b)
    }

    const stop = () => {
        clearTimeout(timer)
        timer = null;
    }
    return {start, stop}
}

const {start, stop} = mySetInterval(() => {console.log(123), 1000, 2000})

setTimeout(() => {
 stop()
}, 10000)

上一篇 下一篇

猜你喜欢

热点阅读