Issue with console output

console.log("first");
setTimeout(function() {
    console.log("second");
}, 0);
console.log("third");

output

first
third
second

Query

0 seconds is not a delay at all . expected output should have been

first
second
third

Could you please explain why it did not work out expected way ?

The timeout doesn’t start counting until after the script has completed, and most browsers don’t do a zero timeout, for performance reasons. You can learn more about this at the Reasons for delays longer than specified section of the setTimeout documentation page.

If the script is big to execute …Will the setTimeout still wait until completed ?

setTImeout always waits until the current script is complete, even when it’s a big one.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.