I have a for loop that i need to use to iterate through 6 arrays of equal length at the same time but at set intervals. I’m using Javascript. what i am having trouble with is implementing the intervals. Basically what i am trying to do is make the for loop iterate through each array at an interval of 1000ms, so that it prints out the console logs at a rate of 1000ms. The ‘iteration complete’ log only after the array is done. meaning after every index has been iterated through at a rate of 1000 ms per index
if anyone has any advice please i would greatly appreciate your input.
const noteW = [1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1]
const noteE = [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1]
const noteR = [1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1]
const noteI = [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1]
const noteO = [1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1]
const noteP = [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1]
for (i=0;i<noteW.length;i++){
if (noteW[i] === 1) {
console.log('shieeet1');
}
if (noteE[i] === 1) {
console.log('shieeet2');
}
if (noteR[i] === 1) {
console.log('shieeet3');
}
if (noteI[i] === 1) {
console.log('shieeet4');
}
if (noteO[i] === 1) {
console.log('shieeet5');
}
if (noteP[i] === 1) {
console.log('shieeet6');
}
console.log('Iteration complete');
}
I have tried using setintervals but its not working for some reason.
2
Answers
You can achieve your purpose by using a
setTimeout
withPromise
which resolves after1
second.A shorter version of the working code will look like:
Alternative solution:
You might be using
setInterval
wrongly because of which it was not working for you. Here’s how you can use it:From what I understand from your question, you want to have only one message each second.
IMHO, the simplest is to use a generative function.