JavaScript Function Queue

前端 未结 6 2137
小蘑菇
小蘑菇 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:10

    You could create a Queue function:

    function Queue(arr) {
        var i = 0;
        this.callNext = function() { 
            typeof arr[i] == 'function' && arr[i++]();
        };
    }
    

    So if these were your functions...

    function f1() {
        alert(1);   
    }
    
    function f2() {
        alert(2);   
    }
    
    function f3() {
        alert(3);   
    }
    

    ... you just pass them (their references) inside a new Queue instance:

    var queue = new Queue([f1, f2, f3]);
    

    Then you execute callNext() to call the functions sequentially:

    queue.callNext();
    queue.callNext();
    queue.callNext();
    

    Live demo: http://jsfiddle.net/CEdPS/3/

提交回复
热议问题