Javascript 如何顺序处理循环中的异步函数
我试图改变文本,使它们一次发生一个,几乎是以连续的方式Javascript 如何顺序处理循环中的异步函数,javascript,Javascript,我试图改变文本,使它们一次发生一个,几乎是以连续的方式 columns.forEach((x) => { setTimeout(() => { x.style.color="red" }, 2500) }) 然而,这只是延迟了它们在2500毫秒之后的发生,然后在2500毫秒之后,它们都会同时发生变化 方法将索引值作为第二个参数传递。您可以将其乘以某个常数来展开计时器: columns.forEach((x, index) => { s
columns.forEach((x) => {
setTimeout(() => {
x.style.color="red"
}, 2500)
})
然而,这只是延迟了它们在2500毫秒之后的发生,然后在2500毫秒之后,它们都会同时发生变化 方法将索引值作为第二个参数传递。您可以将其乘以某个常数来展开计时器:
columns.forEach((x, index) => {
setTimeout(() => {
x.style.color="red";
}, 2500 + index * 500);
});
承诺
使用async/await
,这样做看起来更自然,也更容易遵循/调试
const columns=document.querySelectorAll(“td”);
const sleep=(ms)=>新承诺(r=>setTimeout(r,ms));
异步函数run(){
for(列的常数c){
等待睡眠(2500);
c、 style.color='red';
}
}
run()代码>
td{
边框:1px纯黑;
填充物:5px;
保证金:3倍;
}
1.
2.
3.
4.
5.
6.
7.
像这样的东西怎么样
# cat forEachAsync.js
function forEachAsync(array, fun, cb) {
var index = 0;
if (index == array.length) {
cb(null);
return;
}
var next = function () {
fun(array[index], function(err) {
if (err) {
cb(err);
return;
}
index++;
if (index < array.length) {
setImmediate(next);
return;
}
//We are done
cb(null);
});
};
next();
}
var columns = [1,2,3,4,5]
forEachAsync(columns, function(e, cb) {
console.log('changing column: ' + e);
// let them know we have done with this
// entry so we can start processin the
// next entry.
cb();
}, function(err) {
if (err) {
console.log('Failed in the process' + e.toString());
return;
}
console.log('## done ##');
});
# node forEachAsync.js
changing column: 1
changing column: 2
changing column: 3
changing column: 4
changing column: 5
## done ##
#
#cat forEachAsync.js
函数forEachAsync(数组、fun、cb){
var指数=0;
if(index==array.length){
cb(空);
返回;
}
var next=函数(){
fun(数组[索引],函数(err){
如果(错误){
cb(err);
返回;
}
索引++;
if(索引<数组长度){
立即(下一个);
返回;
}
//我们完了
cb(空);
});
};
next();
}
变量列=[1,2,3,4,5]
forEachAsync(列、函数(e、cb){
console.log('更改列:'+e);
//让他们知道我们已经完成了
//这样我们就可以在
//下一个条目。
cb();
},函数(err){
如果(错误){
console.log('进程中失败'+e.toString());
返回;
}
console.log(“######”);
});
#节点forEachAsync.js
更改列:1
更改列:2
更改栏目:3
更改栏目:4
更改栏目:5
##完成##
#
将(x)
替换为(x,i)
(这是索引),并将延迟设置为2500+i*500
一个队列会更好。我可能也会使用队列,但老实说,这本质上是一个队列。您可以使用承诺:延迟不应该是(索引+1)*2500
?@ibrahimmahrir为什么你认为OP需要每个人之间的2500英镑?@ChrisG OP在他的设置超时中使用2500
。OP想要什么都可以;这只是一个例子。