Browser event loop and my hair

Posted May 28, 20202 min read

Deep understanding of Event Loop

        btn.addEventListener("click", event => {
            setTimeout(() => {console.log("S1")}, 0)
            Promise.resolve(). Then(() => console.log("M1"))
            console.log("L1")
        })
        btn.addEventListener("click", event => {
            setTimeout(() => {console.log("S2")}, 0)
            Promise.resolve(). Then(() => console.log("M2"))
            console.log("L2")
        })

Click btn
Output:L1, M1, L2, M2, S1, S2
The general process is this:

  1. Starting from the browser's event monitoring thread, you see that btn is clicked
  2. Give console.log("S1") to the timer thread in the browser
  3. Add console.log("M1") to the microtask queue
  4. Add console.log("L1") to JS main thread
  5. JS main thread executes tasks output "L1"
  6. The execution stack is empty, the micro queue task is added to it, output "M1"
  7. Give console.log("S2") to the timer thread in the browser
  8. Add console.log("M2") to the microtask queue
  9. Add console.log("L2") to the main JS thread
  10. JS main thread executes task output "L2"
  11. The execution stack is empty, the micro queue task is added to it, output "M2"
  12. The timer thread adds log("S1") and log("S2") to the macro task queue
  13. The JS execution stack is empty, so sequentially output "S1" and "S2"

_Everyone is smart and should understand! _

        btn.addEventListener("click", event => {
            setTimeout(() => {console.log("S1")}, 0)
            Promise.resolve(). Then(() => console.log("M1"))
            console.log("L1")
        })
        btn.addEventListener("click", event => {
            setTimeout(() => {console.log("S2")}, 0)
            Promise.resolve(). Then(() => console.log("M2"))
            console.log("L2")
        })
        btn.click()

Output:L1, L2, M1, M2, S1, S2

Understand the last one, this is easy to understand,
js starts the click event, so there is always a btn.click in the JS main thread before the click event is completed, waiting for the execution to complete and return the result.
The general process is

  1. S1 enters the macro task queue
  2. M1 enters the microtask queue
  3. Output L1
  4. S2 enters the macro task queue
  5. M2 enters the microtask queue
  6. Output L2
  7. The tasks in the microtask queue are added to the JS execution stack in turn, and output M1, M2
  8. The tasks in the macro task queue are added to the execution in sequence, outputting S1, S2

Chikusu, I have less hair. . .