0

How can I do this? How can I delay outer loop until inner for loop will finish taking in mind that I want to delay each inner for loop iteration for 2 seconds? Result which I want to achieve:

outer loop prints in console: 0

outer loop awaits until inner loop will finish.

inner loop prints: 0, 1, 2 with 2 seconds delay.

then outer loop prints: 1.

outer loop awaits until inner loop will finish.

inner loop prints: 0, 1, 2 with 2 seconds delay.

And so on.

for (var i = 0; i < 3; i++)
  {
    alert(i);
    for (var j = 0; j < 3; j++)
      {
        alert(j);
      }
    }

3
  • So what you're really asking for are synchronous timeouts, yes? Commented Jan 19, 2017 at 23:40
  • See here: stackoverflow.com/a/37563825/4987197 and here: stackoverflow.com/a/1776729/4987197 Commented Jan 19, 2017 at 23:44
  • Use recursion, not loops. You then can easily continue asynchronously. Commented Jan 20, 2017 at 2:23

1 Answer 1

0

As mentioned in Synchronous delay in code execution you can have a wait function and include it in your code.

function wait(ms) {
    var start = Date.now(),
        now = start;
    while (now - start < ms) {
      now = Date.now();
    }
}

for (var i = 0; i < 3; i++)  {
  alert(i);
  for (var j = 0; j < 3; j++) {
    alert(j);
    wait(2000);
  }
}
Sign up to request clarification or add additional context in comments.

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.