如何在多个函数完成随机超时后运行语句
How do I run a statement after multiple functions are done with random timeouts?
我得到了这个代码:
'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/
相关文章:
- $(document).height()在刷新时随机化值(Safari 5.1.10)
- 使用当前日期生成随机id
- 使用优化器在慢速连接上加载main.js时需要js超时
- 从a-z中随机选择一个字母
- RequireJ无法随机加载脚本
- 单击按钮时显示随机字符串
- Ajax更新面板随机错误'PRM_MissingPanel'
- 如何检查if/else语句中的随机条件
- 是否可以自动拉取“随机”;标签“;从一长串文本中提取
- 当浏览器控制台未打开时,为什么要求会导致Internet Explorer 9超时
- 如何使用D3生成特定范围内的随机颜色
- 如何在 Javascript/jQuery 中获取一些随机下拉列表的选定值
- 在固定位置显示随机图像
- 超时功能的性能
- 有效地获取两个区间之间的随机整数
- 如何获得随机灯光颜色
- 设置随机数,然后每5秒随机减少一次,直到达到0(javascript)
- 使用javascript和随机暂停/超时快速循环文本
- 使用 Node.JS 设计机器人,这些机器人以随机超时和通用例程运行
- 如何在多个函数完成随机超时后运行语句