二、输出顺序(console.log、settimeout、promise、nextTick)

macro-task(宏任务):包括整体代码script,setTimeout,setInterval
micro-task(微任务):Promise,process.nextTick

process.nextTick:process.nextTick(callback)类似node.js版的"setTimeout",在事件循环的下一次循环中调用 callback 回调函数。
javascript是单线程
setTimeout:因为要入微任务队列,即使是0最快也要4ms,要等待出队

image.png

1、先执行整体代码这个宏任务,再执行立即执行的console等,再执行里面的微任务
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

你可能感兴趣的:(二、输出顺序(console.log、settimeout、promise、nextTick))