preface

The first thing to be clear about is that both microtasks and macro tasks are part of asynchronous programming. The microtasks go directly to the task Queue, and the macro tasks go to the microtasks after the execution of the Web APIs. > < p style = “max-width: 100%; clear: both

  • Macro tasks: setInterval, setTimeout, DOM events, Ajax requests
  • Microtasks: Promise, async/await

JavaScript execution order

  1. The main thread executes from the bottom down
  2. When an asynchronous task is encountered, place the microtask and macro task in accordance with the rules
  3. After the main thread completes execution, the tasks in the task queue enter the main thread
  4. Repeat Step 1
  5. Until both the main thread and the task queue have finished executing
  6. The macro task enters the task queue
  7. The task in the task queue enters the main thread

Let’s take a look at the order of js execution

console.log('start')

// The setTimeout callback is a macro task, and the callback queue is queued
// The callback function is copied easily
setTimeout(timeout = () = > {
  console.log('setTimeout')},0)

// The Promise callback is a microtask that executes directly at the end of this call
// Then assigns a function to an object just for the sake of explanation
Promise.resolve()
  .then(promise1 = () = > {
    console.log('promise1')
  })
  .then(promise2 = () = > {
    console.log('promise2')})console.log('end')

// global start
// global end
// promise1
// promise2
// setTimeout
Copy the code