How can I make a loop pause when a certain condition is satisfied? In the example below loop just shows all values at once while I want it to stop any time it gets across specific value (e.g. 2):
a = [1,1,1,2,1,1,1,3,4,2,1]
for (var i = 0; i < a.length; i++) {
if(a[i] == 2){
setTimeout(console.log(a[i]), 1000)
}else{
console.log(a[i]);
}
};
解决方案
The below creates a function that takes 3 arguments, an array, the amount of time to pause (in milliseconds), and what to pause on. Inside the function it will create a private function that will be used to loop over the array. If the pauseOn value is encoutered a setTimeout is used to recall the loop function after the specified pauseTime
var arr = [1,1,1,2,1,1,1,3,4,2,1];
function iterateArray(arr,pauseTime,pauseOn){
var currentIndex=0;
function loop(){
for(i=currentIndex;i
console.log(arr[i]);
if(arr[i]==pauseOn){
currentIndex = i+1;
setTimeout(loop,pauseTime);
return;
}
}
}
loop();
}
iterateArray(arr,3000,2);