'Why setTimeout(code...,1) is executed first than setTimeout(code... ,0)? [duplicate]

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



Solution 1:[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.

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