'Why setTimeout(fn, 0) and setTimeout(fn, 1) are same while sT(fn, 5) / sT(fn, 6) are not? [duplicate]

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 ?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adrian Brand