使用setTimeout()嵌套回调;

时间:2013-06-17 20:14:37

标签: javascript callback 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);
}

1 个答案:

答案 0 :(得分:1)

方便的是,您可以在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);

}