Nested setTimeout alternative?

前端 未结 6 1586
逝去的感伤
逝去的感伤 2020-12-10 04:22

I need to execute 3 functions in a 1 sec delay.

for simplicity those functions are :

console.log(\'1\');
console.log(\'2\');
console.log(\'3\');
         


        
6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-10 04:37

    You can use something like this with setTimeout:

    var funcs = [func1, func2, func3],
        i = 0;
    
    function callFuncs() {
        funcs[i++]();
        if (i < funcs.length) setTimeout(callFuncs, 1000);
    }
    setTimeout(callFuncs, 1000); //delay start 1 sec.
    

    or start by just calling callFuncs() directly.

    Update

    An setInterval approach (be aware of the risk of call stacking):

    var funcs = [func1, func2, func3],
        i = 0,
        timer = setInterval(callFuncs, 1000);
    
    function callFuncs() {
        funcs[i++]();
        if (i === funcs.length) clearInterval(timer);
    }
    

提交回复
热议问题