views:

41

answers:

2

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??

+3  A: 
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.

Delan Azabani
hey thanks Delan Azabani...it was a very useful answer..
Harish Kurup
No problem. Happy to help.
Delan Azabani
Whilst timeouts are the way to return control to the browser for a while, this won't do what you think due to the [Closure Loop Problem](http://stackoverflow.com/questions/2568966/how-do-i-pass-the-value-not-the-reference-of-a-js-variable-to-a-function). `i` will be `valArray.length` in *every* timeout callback.
bobince
So I should wrap the `setTimeout` call in an anonymous that sets the value? I'll do that now.
Delan Azabani
+6  A: 

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);
vartec
Though this works, using a `for` loop and creating timers of `i * 30000` probably looks nicer than the semi-recursion of your answer.
Delan Azabani
Well, it's not optimal, but IMHO it's closer to the original code from the question.
vartec