Promise, setTimeout, macro task, micro task, synchronous task, asynchronous task

/ * * *@file Promise, setTimeout, macro task, micro task problem */

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

for (var i = 0; i < 10000000; i++) {}

console.log(2);

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

Promise.resolve().then(() = > {
  console.log(4);
});

new Promise((resolve, reject) = > {
  console.log(5);
  resolve();
  console.log(6);
}).then(() = > {
  console.log(7);
});

console.log(8);

// Most people's computers run like this:
/ / 2
/ / 5
/ / 6
/ / 8
/ / 4
/ / 7
/ / 1
/ / 3
Copy the code
// Answer: The positions of the last two bits, 1 and 3, are indeterminate, depending on how long the for loop executes
// for execution time >= 20 milliseconds, 1,3 otherwise 3,1

// change the number of iterations for, e.g., I < 100, so that the result is 3,1
Copy the code

What do you need to know to solve the problem?

Do you really understand the two parameters of setTimeout?

    1. The setTimeout function takes two arguments: the message to be queued and an optional time value (default: 0). This value represents the minimum delay for the message to actually join the queue.
    1. If there are no other messages in the queue and the stack is empty, the message will be processed immediately after this period of time has passed. However, if there are other messages, the setTimeout message must wait for the other messages to finish processing.
    1. So the second parameter only represents the minimum delay time, not the exact wait time.