0

I tested this code and the result I expected was getting the Chicken log first, but I was wrong, everytime I run this code I get the Egg log first, does anybody knows whats going on here?

setTimeout(() => {
  console.log("Egg");
}, 1);

setTimeout(() => {
  console.log("Chicken");
}, 0);

Edit: Notice that this behaves differently if those delays are 101ms and 100ms respectively, so the behavior changes even if the difference on the timer is still 1ms

  • 2
    The timeout is not very accurate. It basically is saying next cycle. The documentation on MDN has good explanations on accuracy and delays https://developer.mozilla.org/en-US/docs/Web/API/setTimeout – epascarello Mar 11 '22 at 23:11
  • Also, in firefox it logs chicken first and then egg – Gabriele Petrioli Mar 11 '22 at 23:14
  • `setTimeout` essentially says "run this once at least [delay] has elapsed and the call stack is empty." With very short timeouts like 0 or 1ms they're almost guaranteed to run on the same cycle, and because "Egg" was queued first it runs first. I suspect if you ran the exact same code but reversed the order of the setTimeout calls, chicken would come first. – ray Mar 11 '22 at 23:18
  • See also [setTimeout functions run in wrong order](https://stackoverflow.com/questions/68988101/settimeout-functions-run-in-wrong-order) – Bergi Mar 12 '22 at 00:31

1 Answers1

-1

The time is in milliseconds that the timer should wait before the specified function or code is executed. 1000ms will be 1 sec and since your input to a parameter was 1ms JS just displayed it in the order it was written because 1ms and 0ms were comparable. Moreover, you can use async-await to wait for tasks that would take longer. For instance,

function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function printOnTime() {{
    console.log("Chicken")
    await timeout(1000); 
    console.log("Egg")
}}


printOnTime();

In this example, Chicken will be printed asap however in order to print Egg it will wait for 1 sec (1000ms) and finally print Egg.

Sulav Dahal
  • 129
  • 3
  • 10
  • 1
    But if you set 101ms and 100ms instead of 1ms and 0ms, the first output is Chicken, so the behavior is different even if the difference is also 1ms – Baltazar Andersson Mar 12 '22 at 00:08