简体   繁体   English

如何使setTimeout()函数按顺序工作?

[英]how to make functions with setTimeout() work in sequence?

Let's say I have 4 functions, every each of them has loops inside working with setTimeout() . 假设我有4个函数,每个函数内部都有使用setTimeout()循环。 How do I make those functions to run in sequence and not overlap? 如何使这些功能按顺序运行而不重叠? That is, how do I make each of them execute just after previous one is finished? 也就是说,如何使它们每个都在上一个完成之后立即执行?

function1();
function2();
function3();
function4(); 

Have each function call the next one after they're done. 完成后,让每个函数调用下一个函数。

If you want to make it "dynamic", implement a queue of functions and have each function call the next function in the queue when they're done. 如果要使其成为“动态的”,请实现一系列函数,并在完成后让每个函数在队列中调用下一个函数。 Then you can start a sequenced process by filling the queue and calling the first function. 然后,您可以通过填充队列并调用第一个函数来启动顺序过程。

function function1(cb) {
    if (someCondition) {
        setTimeout(function1, 0);
    } else {
        // we are done
        cb();
    }
}
...

function1(function() {
    function2(function() {
        function3(function() {
            function4();
        });
    });
});

The code does start getting messy if you go too deep so use some kind of flowcontrol like Step . 如果您做得太深,代码的确会变得混乱,因此请使用诸如Step类的流程控制。 Step might not work if it's not node though. 如果不是节点,则步骤可能不起作用。

A simple queue might be : 一个简单的队列可能是:

var queue = {
    items: [],
    add: function() {
        for (var i = 0; i < arguments.length; i++) {
            this.items.push(arguments[i]);
        }
    },
    run: function() {
        var this = that;
        this.items.shift()(function() {
            that.run();
        })
    }
};

queue.add(function1, function2, function3, function4);

Here each function should take a function parameter done as its first argument and that should be called when the function is done. 在这里,每个函数都应将函数参数done作为其第一个参数,并在函数完成时调用它。

You can pass an array of functions, 您可以传递一系列函数,

and functions with arguments as arrays themselves. 并以参数本身作为数组起作用。

Each must return before setting the timer for the next function 每个必须在设置下一个功能的计时器之前返回

function fifo(what, delay){
    if(what.shift){
        var a, f= what.shift() || '';
        if(typeof f== 'function') f();
        else if(f.constructor== Array){
            a= f.splice(1, f.length);
            f[0].apply(this, a);
        }
        if(what.length){
            setTimeout(function(){
                fifo(what, delay);
            },
            delay);
        }

    }
};

function announce(){
    return alert(location.href)
}
var A= [[alert, 1], [alert, 2], announce, [alert, 'That\'s All!']];
fifo(A, 100);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM