JavaScript Function Queue

前端 未结 6 2026
小蘑菇
小蘑菇 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 16:59

    You could use something like this:

    var FunctionQueue = (function(){
        var queue = [];
        var add = function(fnc){
            queue.push(fnc);
        };
        var goNext = function(){
            var fnc = queue.shift();
            fnc();
        };
        return {
            add:add,
            goNext:goNext
        };
    }());
    

    and use it like this:

    var fnc1 = function(){
        window.setTimeout(function(){
            alert("1 done");
            FunctionQueue.goNext();
        }, 1000);
    };
    
    var fnc2 = function(){
        window.setTimeout(function(){
            alert("2 done");
            FunctionQueue.goNext();
        }, 5000);
    };
    
    var fnc3 = function(){
        window.setTimeout(function(){
            alert("3 done");
            FunctionQueue.goNext();
        }, 2000);
    };
    
    FunctionQueue.add(fnc1);
    FunctionQueue.add(fnc2);
    FunctionQueue.add(fnc3);
    FunctionQueue.goNext();
    

    Edit after a few years: Another way people are approaching this is to pass in a next function that you can call to continue the chain. Like so:

    var Queue = function(arr){
        var index = 0;
        var next = function(){
            if (index >= arr.length) {return;}
            arr[index++](next);
        };
        return next;
    };
    
    var fn1 = function(next){
        console.log("I am FN1");
        next();
    };
    
    var fn2 = function(next){
        console.log("I am FN2");
        setTimeout(next,1000);
    };
    
    var fn3 = function(next){
        console.log("I am FN3");
        setTimeout(next,3000);
    };
    
    var fn4 = function(next){
        console.log("I am FN4");
        setTimeout(next,1000);
    };
    
    Queue([fn1, fn2, fn3, fn4])();
    

提交回复
热议问题