Question

I want to stop the loop for 1 minute and after one minute I want the loop to execute the next instruction. I tried the following code but it is not working. Please help me, what should I do?

   for (j = 0; j < 10; j++) {
             setTimeout(function(){alert("Hello")}, 3000);
            $("#counter").text(j);
        }
Was it helpful?

Solution

You can use following pseudo code to execute your code after 1 minute

var timer = setInterval(function(){
 //your code
 if(//some_condition for breaking interval loop) {
   clearTimeout(timer);
 }
},60000);

OTHER TIPS

Another approach:

var end = 10;

function doThings( start ) {
   for( var i = start; i < end; i++) {
       alert(i);
       if( 5 === i ) {
           setTimeout(function(){ doThings(i+1); }, 5000);
           break;
       }
   }
}

Edit: Well, here a more general version:

function delayedLoop( start, end, body, delay ) {
   for( var i = start; i < end; i++) {
       if( false === body( i ) ) {
           setTimeout(function(){ 
               delayedLoop(i+1, end, body, delay); 
           }, delay);
           break;
       }
   }
}

Usage:

delayedLoop(0, 10, function( i ){
    alert(i);
    if( i === 5 ) {
        return false;
    }
}, 2000);

You cannot freeze the execution like this in Javascript. You have to organise your code differently. For example:

function startLoop(startIndex) {
    for (var j = startIndex || 0; j < 10; j++) {
        if (/* condition to break the loop */) {
            setTimeout(function () {
                startLoop(j);
            }, 3000);
            break;
        }
        $("#counter").text(j);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top