event-loop

166 阅读2分钟

event-loop

event-loop.png

  • 同步和异步任务分别进入不同的执行"场所",同步的进入主线程,异步的进入Event Table并注册函数

  • 当指定的事情完成时,Event Table会将这个函数移入Event Queue。

  • 主线程内的任务执行完毕为空,会去Event Queue读取对应的函数,进入主线程执行。

  • 上述过程会不断重复,也就是常说的Event Loop(事件循环)。

event-loop开始的时候,会从全局一行一行的执行,遇到函数调用,会压入到调用栈中,被压入的函数被称之为帧,当函数返回后会从调用栈中弹出。

function fun1(){
    console.log(1)
}
function fun2(){
    console.log(2)
    fun1()
    console.log(3)
}
func2() //输出结果:2,1,3

微任务与宏任务

image.png

遇到宏任务,先执行宏任务,将宏任务放入eventqueue,然后在执行微任务,将微任务放入eventqueue最骚的是,这两个queue不是一个queue。当你往外拿的时候先从微任务里拿这个回掉函数,然后再从宏任务的queue上拿宏任务的回掉函数。

js中的异步操作,例如fetch、setTimeout、setInterval 压入到调用栈中的时候,里面的消息会进入到消息队列中,消息队列中的任务会等到调用栈清空后再执行

function fun1(){
    console.log(1)
}
function func2(){
    setTimeout(()=>{
        console.log(2)
    },0)
    func1()
    console.log(3)
}
func2() //输出结果:1,3,2

promise、async、await的异步操作会加入到微任务中,会在调用栈清空的时候立即执行 调用栈中加入的微任务会立即执行

var p = new Promise(resolve =>{
    console.log(4)
    resolve(5)
})
function func1(){
    console.log(1)
}
function func2(){
    setTimeout(() =>{
        console.log(2)
    },0)
    func1()
    consoel.log(3)
    p.then(resolve =>{
        console.log(resolve)
    })
]
func2() //输出结果:4,1,3,5,2
console.log('1');

setTimeout(function() {
    console.log('2');
    process.nextTick(function() {
        console.log('3');
    })
    new Promise(function(resolve) {
        console.log('4');
        resolve();
    }).then(function() {
        console.log('5')
    })
})
process.nextTick(function() {
    console.log('6');
})
new Promise(function(resolve) {
    console.log('7');
    resolve();
}).then(function() {
    console.log('8') 
})

setTimeout(function() {
    console.log('9');
    process.nextTick(function() {
        console.log('10');
    })
    new Promise(function(resolve) {
        console.log('11');
        resolve();
    }).then(function() {
        console.log('12')
    })
})
//执行结果:1,7,6,8,2,4,3,5,9,11,10,12