宏任务和微任务

#macrotask(宏任务) 与 microtask(微任务)
macrotask(宏任务)
microtask(微任务)
两者都是用来表示异步任务的分类

在挂起任务时,JS引擎会将所有任务按照任务类别分类分到这两个任务队列中

首先在 macrotask(宏任务)的队列中(这个队列也被称为task queue) 取出 第一个任务 进行执行,

执行完成后

取出 microtask(微任务)的队列中的所有任务并按照顺序执行

执行完成后
(ui试图更新)

再从 macrotask(宏任务)的队列中 取出 一个任务 进行执行,

执行完成后
(ui试图更新)

再取出 microtask(微任务)的队列中的所有任务并按照顺序执行

周而复始

………..

直到两个队列中任务都取完执行完成

宏任务包括:
script(整体代码)
setTimeout
setInterval
I/O
UI交互事件
postMessage
MessageChannel
setImmediate(Node.js)

微任务包括:
Promise.then
Object.observe
MutaionObserve
process.nextTick(Node.js)




//主线程直接执行
// 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')
    })
})
//微事件1
process.nextTick(function() {
    // console.log('6');
})
//主线程直接执行
new Promise(function(resolve) {
    // console.log('7');
    resolve();
}).then(function() {
    //微事件2
    // 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

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2019-2021 伯温

请我喝杯咖啡吧~