1

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);
        }

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

0

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);
    }
}

Comments

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.