preface

Recently I was preparing for an interview, and naturally I looked at the macro and micro tasks of the browser and Node.js. I’ve figured out the simplest one, and I think this is a very easy one to understand and share with you.

The experimental code

  1. Experiment Code 1

  2. Experiment Code 2

A simple introduction

I’ll cover the simplest case and then add node.js and more.

Highlight: macro task and micro task are two queues respectively. When one macro task is completed, all micro tasks will be listed and executed.

What is a macro task

  1. The main thread
  2. setTimeoutThe function inside
  3. setIntervalThe function inside

What are microtasks

  1. The then, catch function of promise

Note ⚠ ️

1: New Promise is not a microtask. Then, catch is. 2. The then and catch of a promise will return a new promise (convenient for chain calls) and change the current promise state from pending to fulfilled or Rejected.

Experiment code 1 parsing

  1. First we execute the main thread code

    currMacro = 'Main thread'
    macroList = []
    microList = []
    Copy the code
  2. Upon encountering the first timer, put timer 1 on the macro task queue and continue executing the main thread

    currMacro = 'Main thread'
    macroList = ['Timer 1']
    microList = []
    Copy the code
  3. When I encounter a new Promise, notice that this is not a microtask, this is a normal statement in the main thread, which I execute directly. Then put the subsequent “then” into the microtask.

    currMacro = 'Main thread'
    macroList = ['Timer 1']
    microList = ['Then of the promise in the main thread']
    Copy the code
  4. Run the following two timers and place them in macroList.

    currMacro = 'Main thread'
    macroList = ['Timer 1'.'Timer 2'.'Timer 3']
    microList = ['Then of the promise in the main thread']
    Copy the code
  5. At the end of the execution, the main thread is finished and we need to perform all the microtasks.

    currMacro = null
    macroList = ['Timer 1'.'Timer 2'.'Timer 3']
    microList = []
    Copy the code
  6. Then execute timer 1 and put the promise’s THEN in the microList

    currMacro = 'Timer 1'
    macroList = ['Timer 2'.'Timer 3']
    microList = ['Then of the Promise in timer 1']
    Copy the code
  7. Then timer 1 runs out and performs all the microtasks.

  8. ···, the following content is similar, I will not say.

Here are the results of experiment 1 👇 :

Experiment code 2 parsing

Answer first:

You can think of your own macro and micro task queues. Note that many “then” tasks are performed, and subsequent “then” or “catch” is added to the list of microtasks, so the following microtasks cannot be performed until all the “then” tasks are completed.