Harish Kurup
Harish Kurup

Reputation: 7505

how to stop a javascript loop for a particular interval of time?

i am using javascript for loop, to loop through a particular array and alert it's value. I want that after every alert it should stop for 30 seconds and then continue...till the end of loop. my code goes here..

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

i have used setTimeout() function, but it is not working...as loop end iterating but do not pause for 30seconds interval... is there any other way such as sleep function in PHP??

Upvotes: 5

Views: 3188

Answers (2)

Delan Azabani
Delan Azabani

Reputation: 81384

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

Edited to fix the closure loop problem.

Upvotes: 11

vartec
vartec

Reputation: 134601

There is no sleep function in JavaScript. You can refactor above code to:

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);

Upvotes: 6

Related Questions