2

When I execute the three lines below, in order, they output in the order 3, 1, 2. Should the order not be 3, 2, 1, since the first line has a longer delay than the second (1ms vs. 0ms)?

setTimeout(() => console.log('1'), 1)
setTimeout(() => console.log('2'), 0)
console.log('3')
AbsoluteBeginner
  • 2,160
  • 3
  • 11
  • 21
Brandon McConnell
  • 5,776
  • 1
  • 20
  • 36
  • try bigger intervals. 0 and 1 are too small to be a noticeable difference – blurfus Aug 30 '21 at 17:29
  • 3
    See [What is minimum millisecond value of setTimeout?](/q/9647215/4642212). – Sebastian Simon Aug 30 '21 at 17:34
  • Also, there are delays in execution time for various reasons: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#reasons_for_delays – blurfus Aug 30 '21 at 17:35
  • 1
    @blurfus 1 & 2 work, so why shouldn't 0 & 1 ? – Alexandre Elshobokshy Aug 31 '21 at 09:47
  • @AlexandreElshobokshy True. It even seems a bit nonsensical that a delay of `0` wouldn't execute in its original order since it techn ical has no delay. I guess even using a `setTimeout` at all causes the code to defer until all other top-level scripts have run first. – Brandon McConnell Aug 31 '21 at 13:47
  • good point. I am guessing if you try them in a loop 20 times you might get different results (due to the execution delays) - sometimes related to a specific browser implementation, sometimes due to other activities happening at the same time - like writing to console - which can cause a slight delay... I am thinking the difference between the two is so minimal that you might not get consistent results. – blurfus Aug 31 '21 at 15:13

0 Answers0