Event Loop

Functions: JS is a single-threaded language, resulting in the execution of time-consuming procedures will be waiting, affecting the user experience. So the Event loop was created to solve this problem

New mechanism in ES6
  • Macrotask: Script main code block, setTimeout, setInterval, requestAnimationFrame, SetimMediate in Node, etc.
  • Microtask: promise. then catch finally, MutationObserver, process.nextTick in Node, etc.

Microtasks are executed after corresponding macro tasks

console.log(1)
setTimeout(() = > {
    console.log(2)})new Promise(resolve= > {
    console.log(3)
    resolve()
}).then(() = > {
    console.log(4)
    
    Promise.resolve()
    .then(() = > {
        console.log(5)
    })
    .then(() = > {
        console.log(6)})})console.log(7)

/ / the result
1 3 7 4 5 6 2
Copy the code
  1. Macro task execution (javascript)console.log(1)
    • Macrotask Queue []
    • Microtask Queue []

    console 1

  2. Macro task execution (setTimeout) generates a callback function, which is arranged injavascriptbehind
    • Macrotask Queue [SetTimeout javascript,]
    • Microtask Queue []
  3. The microtask Promise is executed synchronouslyconsole.log(3)And the.thenPut into the microtask queue
    • Macrotask Queue [SetTimeout javascript,]
    • Microtask Queue [log(4).then(log(5)).then(log(6))]

    console 1 3

  4. Synchronous executionconsole.log(7)
    • Macrotask Queue [SetTimeout javascript,]
    • Microtask Queue [log(4).then(log(5)).then(log(6))]

    console 1 3 7

  5. To perform firstjavascriptThe micro tasksconsole.log(4)And generate new microtasks.then
    • Macrotask Queue [SetTimeout javascript,]
    • Microtask Queue [then(log(5)).then(log(6))]

    console 1 3 7 4

  6. Perform javascript microtasksconsole.log(5)And generate new microtasks.then
    • Macrotask Queue [SetTimeout javascript,]
    • Microtask Queue [.then(6)]

    console 1 3 7 4 5

  7. Perform javascript microtasksconsole.log(6).javascriptWhen the macro task is complete, remove the execution stack
    • Macrotask Queue [SetTimeout javascript,]
    • Microtask Queue [.then(6)]

    console 1 3 7 4 5 6

  8. Execute the next macro tasksetTimeout ,consol.log(2)
    • Macrotask Queue [setTimeout]
    • Microtask Queue []

    console 1 3 7 4 5 6 2

  9. The execution is complete.
You can think of a browser as an inn,'A loving family'Check-in is thought of as a macro task,Family membersThere may be several microtasks (such as getting a pot first) that may spawn new microtasks (after getting a pot of water) and there may be more'Happy family'But you can't wait for another family while you're fetching water. You have to let them get in line first'A loving family'After the microtask is completed, another macro task is executedCopy the code

Mirror: segmentfault.com/a/119000001…