3

why console order is 2 3 1 ? each script seem to wait promise task,

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script>
      setTimeout(() => console.log(1), 0);
      Promise.resolve(2).then(console.log);
    </script>
    <script>
      console.log(3);
    </script>
  </head>
  <body></body>
</html>

I thought it would be 3 2 1. but obviously I was wrong

why 2 output before 3, Promise then callback will exec in nexttick,and console.log(3); is sync task.

bigboss
  • 155
  • 8
  • 1
    the most meaningful thing to say there it's why `setTimeout` doesn't execute the code immediately as someone would expect. From [mdn](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) _"If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle."_ . [Here](https://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful) on SO more details about that. To further expand "next event cycle", it means that the func is queued to be executed as soon as the current script finished execution – Diego D Feb 21 '23 at 08:44

1 Answers1

0

the event loop in macrotask include the rendering. you can see the standard of Processing model

so the order is
setTimeout => micro task promise => render script => setTimeout function exec