我想并行运行几个任务,并使用mbostock.I的queue.js,我使用Sleep()运行下面的代码,因此期望其他较轻的任务在繁重的任务之前完成,而在相同的time.But上执行的所有任务都会导致任务的顺序执行
2 1 test.html:128
1000 2 test.html:134
4 3 test.html:128
3000 4 test.html:134
6 5 test.html:128当我期待类似的事情(同时执行所有任务,但较轻的任务提前完成):
2 1 test.html:128
4 3 test.html:128
6 5 test.html:128
1000 2 test.html:134
3000 4 test.html:134我做错了什么?代码:
function Sleep(ms) {
var d1 = new Date().getTime();
var d2 = new Date().getTime();
while( d2 < (d1 + ms) ) {
d2 = new Date().getTime();
}
return;
}
var tmp_list = [];
var normal = function(src){
tmp_list.push(src);
console.log(src,tmp_list.length);
}
var sleepy = function(src){
Sleep(5000);
tmp_list.push(src);
console.log(src,tmp_list.length)
};
queue().defer(normal,2)
.defer(sleepy,1000)
.defer(normal,4)
.defer(sleepy,3000)
.defer(normal,6)
.awaitAll(function(){});发布于 2014-03-24 07:04:33
Javascript的并发模型与其他语言略有不同。
在Javascript中,除了输入/输出之外,所有东西都同步运行。这个输入/输出通常采用AJAX调用的形式。您还可以使用setTimeout函数显式地生成控件。
在您的示例中,您在Sleep函数中创建一个繁忙的循环:
function Sleep(ms) {
var d1 = new Date().getTime();
var d2 = new Date().getTime();
while( d2 < (d1 + ms) ) {
d2 = new Date().getTime();
}
return;
}这将保持CPU忙碌的嗡嗡前进和不屈服的控制,直到它完成。但是,如果您确实希望等待任务结束,则必须使用queue库提供的queue库提供给正在调用的函数的setTimeout,并使用setTimeout
/* cb :: function (err, result) is added by queue library to the arg list */
function sleepy = function (src, cb) {
setTimeout(function () {
tmp_list.push(src);
console.log(src, tmp_list.length);
cb(); // no errors
}, 5000);
}此外,我怀疑.awaitAll之后的函数也没有被调用(因为您没有使用队列的回调)。尝试在其中放置一个console.log来验证这一点。
https://stackoverflow.com/questions/22602732
复制相似问题