美文网首页
实现 setInterva

实现 setInterva

作者: bestCindy | 来源:发表于2020-10-10 22:56 被阅读0次

    setTimeout 实现递归实现

    const mySetInterval = (cb, time) => {
        const fn = () => {
            cb();
            setTimeout(() => {
                fn();
            }, time);
        }
        fn();
    }
    mySetInterval(() => {
        console.log(new Date())
    }, 1000)
    

    非递归实现

    const setInterval1 = (func, interval) => {
        let startTime = Date.now();
        const config = { shouldStop: false };
        while (!config.shouldStop) {
            if (Date.now() - startTime >= interval) {
                func();
                startTime = Date.now();
            }
        }
        return config;
    }
    
    const myClearInterval = config => { config.shouldStop = true; }
    

    相关文章

      网友评论

          本文标题:实现 setInterva

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