JavaScript Function Queue

前端 未结 6 2025
小蘑菇
小蘑菇 2021-01-18 16:40

I have a ton of functions that need to run in succession, but not before the other has completed. What I need is a way to queue these functions to run only after the previou

6条回答
  •  抹茶落季
    2021-01-18 17:13

    You don't need all that machinery, just put your functions in an array. Then you can loop over them.

    var runThese = [
        Function1,
        Function2, 
        Function3,
        Function4,
        Function5
    ];
    

    JavaScript is single-threaded so you're guaranteed one finishes before the next starts.

    for (var i = 0; i < runThese.length; i++) {
        runThese[i]();
    }
    

    Or since your functions have deterministic names, you could avoid the array altogether:

    for (var i = 1; i <= 5; i++) {
        window["Function" + String(i)]();
    }
    

提交回复
热议问题