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??
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.
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.
A for..in loop can't use break. It's not possible to end it in this way.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With