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

标签 javascript asynchronous

我得到了这段代码:

'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()。

但是,如果您坚持只使用原始回调,我会将 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);

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

关于javascript - 在随机超时完成多个函数后,如何运行语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25731025/

相关文章:

javascript - 简单的 Javascript 不执行任何操作,控制台中没有错误

javascript - 避免在 iframe 中重复使用 Javascript

asynchronous - 如何有效地解码 gobs 并等待更多通过 tcp 连接到达

asynchronous - F# 是否有 Async.Sequential 来匹配 Async.Parallel?

ajax - 如何基于异步源设置初始值,例如使用 redux-form 的 ajax 调用

javascript - 正则表达式匹配不需要的字符串

javascript - 更新 Windows Azure 移动服务中的查询 javascript/html

javascript - 不允许用户选择网页的一部分

c# - 实现搜索和突出显示 - 当突出显示缓慢时如何避免延迟?

javascript - Meteor Method 中的 .forEach 无法返回