5

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

Harish Kurup
  • 7,257
  • 19
  • 65
  • 94

2 Answers2

11
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
  • 79,602
  • 28
  • 170
  • 210
  • 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 May 29 '10 at 11:20
  • So I should wrap the `setTimeout` call in an anonymous that sets the value? I'll do that now. – Delan Azabani May 29 '10 at 11:21
6

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
  • 131,205
  • 36
  • 218
  • 244
  • 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 May 29 '10 at 11:09
  • Well, it's not optimal, but IMHO it's closer to the original code from the question. – vartec May 31 '10 at 07:38