How to stop javascript loop for a specific time interval?

I use javascript for a loop to iterate over a specific array and warn its value. After each warning, I want it to stop for 30 seconds and then continue ... until the end of the cycle. my code goes here.

    for(var i=0; i<valArray.lenght; i++)
    {
        alert("The value ="+valArray[i]);
        //stop for 30seconds..      
    }

I used the setTimeout () function, but it doesn’t work ... like loop termination, but doesn’t stop at the 30 second interval ... is there any other way, for example, the sleep function in PHP?

+5
source share
2 answers
for (var i = 0; i < valArray.length; i++)
  (function(i) {
    setTimeout(function() {
      alert(valArray[i]);
    }, i * 30000);
  })(i);

Edited to fix a circuit problem.

+8
source

JavaScript has no sleep function. You can reorganize the code above:

function alert_and_sleep(i) {
   alert("The value ="+valArray[i]);
   if(i<valArray.length) {
     setTimeout('alert_and_sleep('+(i+1)+')',30000);
   }
}
alert_and_sleep(0);
+6
source

All Articles