-3

Below are the 2 scenarios

for (var i=0; i<3; ++i)
{
   let num = i;
   setTimeout(function() { alert(num); }, 10);
}

Output series: Alerts : 0,1,2

for (var i=0; i<3; ++i)
{
   // variables introduced in this statement
   // are scoped to the block containing it.
   let num = i;
   setTimeout(function() { alert(num); }, 10);
}

Output series: Alerts : 0,2,1

Two identical code but with different result.

Any Idea ???

Kathir
  • 1,212
  • 15
  • 25
  • 3
    Your two code blocks look identical to me. And, do NOT use `alert()` if you want to test real javascript timing because alert blocks and stops things. Use `console.log()` instead. – jfriend00 Apr 25 '18 at 02:34
  • Is it me only who is not able to find difference between above two examples? – Nitishkumar Singh Apr 25 '18 at 02:36
  • 1
    @NitishkumarSingh the comments. – Marcos Casagrande Apr 25 '18 at 02:38
  • I also vote for "the two pieces of code are identical" – Jaromanda X Apr 25 '18 at 02:46
  • 1
    I think what he has put is extremely clear. Same code, different results. He may have been able to word it a little better, but just because you don't understand something straight away doesn't mean it should be closed. Surprising, considering that you guys have such high rep. – Matt Way Apr 25 '18 at 02:52
  • https://stackoverflow.com/questions/1776239/are-equal-timeouts-executed-in-order-in-javascript or https://stackoverflow.com/questions/11771558/execution-order-of-multiple-settimeout-functions-with-same-interval or others – epascarello Apr 25 '18 at 03:05

1 Answers1

1

I think the answer to your question might be the nature of using very low timeouts with setTimeout, and a non guaranteed ordering.

See this link: https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers

And notice this line:

This API does not guarantee that timers will run exactly on schedule. Delays due to CPU load, other tasks, etc, are to be expected.

This means that depending on the circumstances, your identical code blocks could indeed output different results. setTimeout also doesn't guarantee the exact time you use, especially when the timeout is very low (like the 10ms you have chosen).

Matt Way
  • 32,319
  • 10
  • 79
  • 85