Simply put, the order of js execution is as follows:

Execution order

  1. Synchronous programs

  2. process.nextTick

  3. Micro tasks

  4. Macro task

  5. setlmmediate

Macro tasks can be thought of simply as following: setTimeout, Ajax, and reading files

Then > MutationObserver > setImmediate > setTimeout

Microtasks: code in promise.then

At this point, the delay device needs to pay attention

When executing a task, the code in the run stack is executed first, and then the code in the task queue is executed as shown below:

When the delay occurs, it will not be immediately put into the task queue, but will be inserted into the task queue after waiting for the end of the delay in the task cycle. If there are other tasks in the task queue before insertion, other tasks will be performed first and then the delay will be executed at last

Here’s the last interview question

setImmediate(() = > {
  console.log(9)})setTimeout(() = > {
  console.log(3)},0)
setTimeout(() = > {
  console.log(4)},100)
console.log(5)
new Promise((resolve) = > {
  console.log(6)
  resolve()
}).then(() = > {
  console.log(7)
})
process.nextTick(() = > {
  console.log(8)})console.log(1)
setTimeout(() = > {
  console.log(2)},0)
setTimeout(() = > {
  console.log(10)},0)
console.log(11)
Copy the code

The outputs are: 5, 6, 1,11,8, 7, 3, 2, 10, 9, 4

There is a small pit here, pay attention to whether the delay timer is delayed, if there is a delay, you need to wait for other tasks to execute