3

I was going through some articles on event loop and tried output of the following:

console.log('print [1]');
setTimeout(() => console.log("print [2]"), 0);
setTimeout(() => console.log("print [3]"), 0);
setTimeout(() => console.log("print [4]"), 0);

console.log("print [5]");

It will output synchronous consoles or macrotask calls before picking timeout logs. It printed as usual:

print [1]
print [5]
print [2]
print [3]
print [4]

Also could understand the following as well:

console.log('print [1]');
setTimeout(() => console.log("print [2]"), 0);
setTimeout(() => console.log("print [3]"), 2); // passed 2ms as the delay
setTimeout(() => console.log("print [4]"), 0);

console.log("print [5]");

print [1]
print [5]
print [2]
print [4]
print [3]

But it got interesting when I passed 1ms as the delay to the second timeout. I was expecting it to behave the same way as passing 2ms delay but instead it behaved as if 0ms was passed.

console.log('print [1]');
setTimeout(() => console.log("print [2]"), 0);
setTimeout(() => console.log("print [3]"), 1);
setTimeout(() => console.log("print [4]"), 0);
    
console.log("print [5]");

print [1]
print [5]
print [2]
print [3]
print [4]

Does something specific happens because of that 1ms or is it some sort of threshold?

Aakash Thakur
  • 3,837
  • 10
  • 33
  • 64
  • 3
    https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Reasons_for_delays_longer_than_specified – Lawrence Cherone Jul 09 '20 at 18:38
  • But documentation says min of 4ms. It showed a different result even at 2ms. Still a little perplexed. – Aakash Thakur Jul 09 '20 at 18:49
  • It may be a rounding thing, im actually seeing it round down or up if ± 2 not 4ms as docs say, taking stack into consideration https://playcode.io/633369/ - setTimeout is not the solution if you're trying to stack things in ms ranges, instead use promises. – Lawrence Cherone Jul 09 '20 at 19:04
  • Note that the two first answers there got it wrong, the real issue is that Chrome does hardcode a minimal timeout of 1ms. The 4ms one is only when you are at 5 levels of nesting. Firefox also has some kind of delay at page load (actually a low priority queue just for that), but I guess that wouldn't affect your code. – Kaiido Jul 10 '20 at 04:57

0 Answers0