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);
      }
    }
Max Naumov
  • 178
  • 12

1 Answers1

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);
  }
}
Yiannis
  • 61
  • 6