事件循环(Event Loop)

 

1.什么是事件循环?

JavaScript为单线程执行的,因此是从上到下依次执行,js分为两个任务,宏任务和微任务promise

首先执行宏任务(第一次就是执行全部的同步代码),再执行全部的微任务,执行完毕以后再次执行post

宏任务,执行完毕再次执行全部的微任务,也就是:spa

宏任务 --> 微任务  -->  宏任务 -->  微任务线程

2.什么是宏任务,微任务?

宏任务:code

script(全局任务), setTimeout, setInterval, setImmediate, I/O, UI rendering.
微任务:
process.nextTick, Promise.then, Object.observer, MutationObserver.

3.案例深刻解读

1
2
3
4
5
6
7
8
9
10
11
12
13
14
setTimeout(function(){
    console.log(1)
},0)
 
new  Promise((resolve,reject)=>{
     console.log(2)
     resolve(3)
     setTimeout(function(){
        console.log(5)
        promise.resolve
     },0)
}).then((val)=>{
     console.log(val)<br> })
console.log(4)

解读:

    首先执行宏任务(同步代码)  :console.log(2)  console.log(4)server

    再执行全部的微任务  console.log(3)blog

    再一次从上到下执行全部的微任务:console.log(1)   console.log(5)事件

    因此正确答案是  2 4  3 1 5ip

 

咱们再加大难度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
console.log( 'start' )
setTimeout(() => {
   console.log( 'setTimeout 1' )
   Promise.resolve().then(() => {
     console.log( 'promise 3' )
   }).then(() => {
     console.log( 'promise 4' )
   }).then(() => {
     setTimeout(() => {
       console.log( 'setTimeout 2' )
       Promise.resolve().then(() => {
         console.log( 'promise 5' )
       }).then(() => {
         console.log( 'promise 6' )
       })
     }, 0)
   })
}, 0)
Promise.resolve().then(() => {
   console.log( 'promise 1' )
}).then(() => {
   console.log( 'promise 2' )
})

解读:ci

    咱们先执行同步代码: start

    微任务:promise 1 ,  promise 2

    宏任务: setTimeout 1

   微任务:promise 3, promise 4

   宏任务:setTimeout 2 , 

  微任务:promise 5,promise 6

正确答案

start promise 1 promise 2 setTimeout 1 promise 3 promise 4 setTimeout 2 promise 5 promise 6
相关文章
相关标签/搜索