0

for (var i = 1; i < 5; i++) {
  console.log(i);
  setTimeout(function() {
    console.log(i);
  }, 3000)
};

first, this code displays the numbers from 1 to 4, and after three seconds - four fives. this is not an obvious sequence of actions. I would suppose the output should be like this:

1 //pause 3s
1
2 //pause 3s
2
3 //pause 3s
3
4 //pause 3s
4

what I need to know about the JS-interpreter to give the correct answer? the question is not at all about closures

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Simply One
  • 25
  • 4
  • 1
    you have a closure over `i`. the deferred call takes the last value of it. – Nina Scholz Feb 24 '20 at 12:24
  • It seems as though the setTimeout function is . blocking so the event loop won't move on until it completes. – Michael Feb 24 '20 at 12:24
  • The first 1 2 3 4 is based on log inside `for` loop. The Remaining four 5's are printed from `setTimeout` initiated in loop. – Nareen Babu Feb 24 '20 at 12:27
  • "_this is not an obvious sequence of actions_", Yes it is. `setTimeout` doesn't block, and the loop was finished before the first timeout will be executed. At that time the variable value has grown to 5. Also, all the timeouts are set sequentially in the loop within less than a millisecond, hence they will fire almost the same time, because they've the same delay set. – Teemu Feb 24 '20 at 12:35
  • **@Teemu**, thanks for the careful reading and your answer. yes, it's a key point that was unclear – Simply One Feb 27 '20 at 07:38

2 Answers2

0

setTimeout delays function call, it doesn't put the actual program to sleep. It is an asynchronous method, if you want to pause your application - do this:

for (var i = 1; i < 5; i++) {
  console.log(i);
  sleep(3000);
  console.log(i);
};
  • Note that most browsers don't support `sleep` ... if you wan't to polyfill, check this article https://www.sitepoint.com/delay-sleep-pause-wait/ – rafaelcastrocouto Feb 24 '20 at 12:39
0

You can use your index to control the time of setTimeout:

for (var i = 0; i < 4; i++) {
  setTimeout(function(ii) {
    console.log(ii);
  }.bind(0, i+1), i*1000)
};
rafaelcastrocouto
  • 11,781
  • 3
  • 38
  • 63