1

It's been a while as such topics haven't been raised since 2011,2012. Now, this code


  setTimeout(()=>{ console.log(1); }, 1);
  setTimeout(()=>{ console.log(2); }, 0);
  setTimeout(()=>{ console.log(3); }, 2);

will print 1-2-3 even though you would expect 2 be logged faster than 1.

You may explain that by pointing out to "All timeouts less than 4ms will be delayed to 4ms".

Or say about 13ms tick, like - by the time second line is executed first line has cleared time and is logged, but no, both this rules won't apply if we use 2-3ms times. In this case all is working as expected

Prove:

  setTimeout(()=>{ console.log(1); }, 3);
  setTimeout(()=>{ console.log(2); }, 2);
  setTimeout(()=>{ console.log(3); }, 2);

Won't apply that rule - 2 gets logged before 1, as ms order dictate.

This behaviour is met in Chrome 84. Firefox is doing all this code in order, no matter what ms are there. 1-2 or 3-2 or 6-5 etc Turns out that 1ms and 0ms for Chrome are same, while 5-6 or 2-3 are different PS: Opera behaves like Chrome as well. Treating 1ms same as 0, while 2ms differs to 1ms

Why ?

Anton
  • 516
  • 1
  • 6
  • 22
  • 1
    There is no guarantee about when a setTimeout will be executed *EXCEPT* that it won't run *before* n (2nd argument) milliseconds from when it is set up. – ControlAltDel Aug 22 '20 at 22:19
  • because they have different JavaScript engine, and your delays are too short to be relevant – Mister Jojo Aug 22 '20 at 22:20
  • @MisterJojo why for Firefox my short delays are relevant ? – Anton Aug 22 '20 at 22:21
  • no, thety are not, even for Firefox – Mister Jojo Aug 22 '20 at 22:24
  • Actually, i got an idea. First of, of course browser engines are different and Firefox deals with this code in other manner producing expected results. As for "why 1 is treated as 0 and 2 is not same as 1" i suggest following. May be 1ms is not enough for browser to parse and execute all code and 1ms times is cleared and run before 2nd line is parsed resulting in console.log(1) being executed aster that console.log(2) while all the rest examples (2ms and more) is enought to parse/execute all code in correct order. – Anton Aug 22 '20 at 22:25
  • @MisterJojo i just executed that code with (1ms and 0ms) in Firefox on 3 computers(1pc and 2 notebooks) - all time i get 0ms console.log before 1ms – Anton Aug 22 '20 at 22:26
  • that's not a proof. delay argument is just indicative, and the setTimeout (or setInterval) methods cannot be used as chronograph – Mister Jojo Aug 22 '20 at 22:31
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/220282/discussion-between-anton-and-mister-jojo). – Anton Aug 22 '20 at 22:33

1 Answers1

0

Because 1ms has passed by the time the queued code blocks are called. Seeing the first one is at the front of the queue and the timeout period has passed it will be executed.

Adrian Brand
  • 20,384
  • 4
  • 39
  • 60