Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 668
Harish Kurup Avatar asked May 29 '10 10:05

Harish Kurup


People also ask

How do you stop intervals after some time?

To stop it after running a set number of times, just add a counter to the interval, then when it reached that number clear it. Save this answer.

How do I pause a JavaScript loop?

You cannot "pause" JavaScript in a web browser. You can, however, setup timers and cause code to be executed at a later point with the setTimeout() and setInterval() APIs available in all browsers.

Can we break for of loop in JavaScript?

A for..in loop can't use break. It's not possible to end it in this way.

How do you stop a looping function?

break terminates the execution of a for or while loop. Statements in the loop after the break statement do not execute. In nested loops, break exits only from the loop in which it occurs. Control passes to the statement that follows the end of that loop.


2 Answers

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.

like image 190
Delan Azabani Avatar answered Sep 18 '22 17:09

Delan Azabani


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);
like image 43
vartec Avatar answered Sep 18 '22 17:09

vartec