JavaScript函数队列 [英] JavaScript Function Queue

查看:72
本文介绍了JavaScript函数队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多需要连续运行的功能,但是在其他功能完成之前没有。我需要的是一种方法,将这些函数排队,只有在上一个函数成功完成后才能运行。有什么想法吗?

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 previous function was successfully completed. Any Ideas?

Function1();
Function2();
Function3();
Function4();
Function5();


推荐答案

您可以使用以下内容:

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
    };
}());

并像这样使用:

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();

几年后编辑:
人们接近这个的另一种方式是传入 next 可以调用以继续链的函数。像这样:

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])();

这篇关于JavaScript函数队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆