js event loop instances resolved

js execution sequence analysis

console.log(1)

setTimeout(()=>{
    console.log(2)
},2000)

setTimeout(()=>{
    console.log(3)
    Promise.resolve().then(()=>{
        console.log(4)
    })
    setTimeout(()=>{
        console.log(5)
    },3000)
},1000)

new Promise((resolve,reject)=>{
    console.log(6)
    resolve()
}).then(()=>{
    console.log(7)
})

console.log(8)

// 输出结果:1,6,8,7,3,4,2,5

image

Synchronization task
  • js single-threaded, interpreted

Asynchronous tasks

MacroTask (Task): macro task.
  • the entire script code, setTimeout, setInterval, setImmediate, requestAnimationFrame, I / O, UI rendering;
MicroTask: micro-tasks.
  • process.nextTick (Node environment), Promise, Object.observe (basic waste)

Resolution:

The first step: perform synchronization tasks and pending asynchronous tasks
  • js is single-threaded, interpreted language, so the start to finish line by line, to meet asynchronous tasks pending asynchronous thread
  • So first sequentially outputs 168
  • Note: Promise and .catch belong in .then micro-task, the callback function itself belongs to synchronize tasks, executed directly on the main thread
Step two: asynchronous task execution queue first macro task
  • Pending asynchronous tasks to asynchronous thread
  • After the end of the asynchronous task execution, to get the result, it will be registered in the asynchronous callback queue
  • Asynchronous queue task priority tasks execute the macro, micro encountered task suspension to micro-task stack until the task is completed after the current macro, micro finished performing all tasks micro task stack,
  • And then perform the macro task queue task of the second macro, repeat the previous step
  • Therefore this process sequentially outputs: 7
The third step: About setTimeout
  • One-time timer, because there is a delay, and therefore on the final execution of the macro task
  • One second delay timer early execution in two seconds delay timer
  • This process thus outputs 34
  • Internal one second timer Timer three seconds, the total delay is longer than two seconds
  • Therefore precedence two-second timer result, after performing one second timer sub-timer (three seconds timer)
  • This process output 25

Note: The order of the consistent implementation of the macro task js, js execution and synchronization tasks in principle
Note: promise that after the implementation of the code in the current script, and immediately executed, it does not participate in the event loop, so its priority is higher than setTimeout
Nature macro task: to participate in the mission of the event loop
The nature of the micro-task: not to participate in the event loop tasks performed directly in the Javascript engine

Guess you like

Origin www.cnblogs.com/nanhuaqiushui/p/11787480.html