美文网首页
setTimeout 模拟 setInterval

setTimeout 模拟 setInterval

作者: McDu | 来源:发表于2021-03-22 16:47 被阅读0次

写一个 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)

相关文章

网友评论

      本文标题:setTimeout 模拟 setInterval

      本文链接:https://www.haomeiwen.com/subject/fyozcltx.html