I want to hold the iteration of the for-loop until the functionality in the previous iteration gets completed. I have seen many questions about setTimeout but none of them has satisfied my requirement. Can anyone help me?
function abcd() {
var exArray = [0, 0, 1, 1, 1, 0, 0, 0];
var index = 0;
for (var i = 0; i < exArray.length; i++) {
if (exArray[i] == 1) {
addDelay(++index);
} else {
console.log('ended at ' + i);
}
}
}
seTimeout functionality is something like this
function addDelay(index) {
setTimeout(function() {
console.log("in Timeout loop:" + index);
}, 2000 * index);
}
The expected output is
ended at 0
ended at 1
in Timeout loop:{{index}} // wait for delay
in Timeout loop:{{index}} // wait for delay
in Timeout loop:{{index}} // wait for delay
ended at 5
ended at 6
ended at 7
But output I see in my console is:
ended at 0
ended at 1
ended at 5
ended at 6
ended at 7
in Timeout loop:{{index}} // wait for delay
in Timeout loop:{{index}} // wait for delay
in Timeout loop:{{index}} // wait for delay
I want the ended at 5 to wait until timeout functionality of 3rd, 4th, 5th array indices. I need someone to help me on this. Thanks in advance.
setTimeoutcode section is well written... try a ES6 approach:setTimeout(() => { console.log('waiting 1 second...'); }, 1000);setTimeoutwill schedule a background task and then return immediately. so your loop continues to run and after the delay the timeout function is executed, so it can't work like that. The best solution in your case might be to get rid of the for loop and replace it by a callback-loop, so after each delayed execution it call the "loop" with the next index until the end of your array.