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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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. i will be valArray.length in every timeout callback.
So I should wrap the setTimeout call in an anonymous that sets the value? I'll do that now.
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);

2 Comments

Though this works, using a for loop and creating timers of i * 30000 probably looks nicer than the semi-recursion of your answer.
Well, it's not optimal, but IMHO it's closer to the original code from the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.