如何在多个函数完成随机超时后运行语句

How do I run a statement after multiple functions are done with random timeouts?

本文关键字:超时 随机 运行 语句 函数      更新时间:2023-09-26

我得到了这个代码:

'use strict';
var total = 0;
console.log("Start of program - total is now: " + total);
setTimeout(function() {
    console.log("function 1");
    total += 10;
}, 500);

setTimeout(function() {
    console.log("function 2");
    total += 50;
}, Math.floor(Math.random() * 1000));

setTimeout(function() {
    console.log("function 3");
    total += 100;
}, Math.floor(Math.random() * 1000));

console.log("End of progam - total is now: " + total);

只有当上面的所有超时都被执行时,我才能运行最后一个console.log?

有几种可能的方法来解决这个问题。如果你有时间的话,我建议你研究Promises,并使用Promise.all().

然而,如果您坚持只使用vanilla回调,我将console.log替换为以下内容:

var countTimeoutsFinished = 0;
function testEndOfProgram() {
    if(countTimeoutsFinished === 3) {
        console.log("End of program - total is now: " + total);
    }
}

然后,在每次超时内,递增countTimeoutsFinished并调用testEndOfProgram():

setTimeout(function() {
    console.log("function 1");
    total += 10;
    countTimeoutsFinished++;
    testEndOfProgram();
}, 500);

当第三次超时完成时,countTimeoutsFinished将为3,然后当您进入testEndOfProgram时,console.log将执行。

正如Kyle所说,您可以使用promise。

使用jQuery运行示例(为了简化,您可以使用任何Promise库)

var总计=0;

console.log("Start of program - total is now: " + total);
var dfd1 = new jQuery.Deferred();
setTimeout(function() {
    console.log("function 1");
    total += 10;
    dfd1.resolve();
}, 500);

var dfd2 = new jQuery.Deferred();
setTimeout(function() {
    console.log("function 2");
    total += 50;
    dfd2.resolve();
}, Math.floor(Math.random() * 1000));

var dfd3 = new jQuery.Deferred();
setTimeout(function() {
    console.log("function 3");
    total += 100;
    dfd3.resolve();
}, Math.floor(Math.random() * 1000));
$.when.apply($, [dfd1, dfd2, dfd3])
.done(function() {
   alert("End of progam - total is now: " + total); 
});

Fiddle:http://jsfiddle.net/3r0ydxg5/