嵌套回调函数setTimeout();



我如何将这条匿名函数定义链重写为单独的函数,使其更易于维护和阅读?谢谢!

function animation(){
    var timeout;
    timeout=timeoutsetTimeout(function(){
        console.log('step1')
        timeout=setTimeout(function(){
            console.log('step2')
            timeout=setTimeout(function(){                                  
                console.log('almost there')
                setTimeout(function(){
                        console.log('grand finale')
                    }, 300);
            }, 1000);

        }, 2000);

    }, 5300);
}

可以方便地使用闭包来代替JS中的IOC或DI:

function animation(){
    var timeout;
    function one(){
        console.log('step1');
        timeout=setTimeout(two, 2000);
    }
    function two(){
        console.log('step2');
        timeout=setTimeout(three, 1000);
    }
    function three(){
        console.log('almost there');
        timeout=setTimeout(four, 300);
    }
    function four(){
        timeout=console.log('grand finale');
    }
   return timeout=setTimeout(one, 5300);
}

最新更新