[英]How to iterate over each object in array one by one not simultaneously in JS?
What i want to achieve: A function that iterates over an array and calls other functions one by one, waits until function is complete before calling another 我要实现的功能:遍历数组并一个接一个地调用其他函数的函数,等到函数完成后再调用另一个函数
Every time the function is called it should go back to the start of the array eg 1, 2, 3, 4
if 5
is added, it should call functions that start from 1
before reaching 5
每次调用该函数时它应该回到该阵列例如开始
1, 2, 3, 4
,如果5
加入,它应该调用,从开始的函数1
到达前5
Here is what i have tried after some searching: 这是我经过一些搜索后尝试过的:
function startFlash(num, value) {
console.log(num);
if (0 < num.length) {
console.log('settimeup');
setTimeout(function () {
sequence.forEach(function (entry) {
setTimeout(function () {
if (entry == "red") {
flashRed();
} else if (entry == "green") {
flashGreen();
} else if (entry == "blue") {
flashBlue();
} else if (entry == "yellow") {
flashYellow();
}
}, 1000)
})
num++;
startFlash(num, value);
}, 1000);
}
}
So startFlash
is being called by a function which uses math.floor
to generate a number between 1-4 and depending on the number, adds the color, red/blue/yellow/green to the array sequence
因此
startFlash
被一个函数调用,该函数使用math.floor
生成一个介于1-4之间的数字,并根据该数字向数组sequence
添加颜色(红色/蓝色/黄色/绿色)
Now the code above calls all method at the same time which is not what i want. 现在上面的代码同时调用所有方法,这不是我想要的。
Heres something else i've tried after doing more searches: 在进行更多搜索后,我尝试了以下其他方法:
if (sequence[sequence.length -1] == "red") {
flashRed();
} else if (sequence[sequence.length -1] == "green") {
flashGreen();
} else if (sequence[sequence.length -1] == "blue") {
flashBlue();
} else if (sequence[sequence.length -1] == "yellow") {
flashYellow();
}
Now this code above only calls the latest value in the array like it suggests, but i need it to start from the first value in the array 现在上面的代码只像建议的那样调用数组中的最新值,但是我需要它从数组中的第一个值开始
Any help? 有什么帮助吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.