# 宏任务和微任务
# 一段代码
console.log('script start');
setTimeout(function () {
console.log('setTimeout');
}, 0);
Promise.resolve()
.then(function () {
console.log('promise1');
})
.then(function () {
console.log('promise2');
});
console.log('script end');
这段代码的输出如下:
// script start
// script end
// promise1
// promise2
// setTimeout
在编译期间已经把代码分成了同步代码、宏任务、微任务
同步代码:
console.log('script start');
console.log('script end');
宏任务:
console.log('setTimeout');
微任务:
console.log('promise1');
console.log('promise2');
浏览器执行顺序:同步代码 -> 微任务 -> 宏任务
# 不同的是
注意下面的输出会不一样
console.log('1'); // 宏任务 同步
setTimeout(function() {
console.log('2'); // 宏任务 异步
})
new Promise(function(resolve) { // 这个是定义
console.log('3'); // 宏任务 同步
resolve();
}).then(function() {
console.log('4') // 微任务
})
console.log('5') // 宏任务 同步
1
3
5
4
2
宏任务:
浏览器 | nodejs | |
---|---|---|
UI render | √ | √ |
I/O | √ | √ |
setTimeout | √ | √ |
setInterval | √ | √ |
RequestAnimationFrame | √ | × |
setImmediate | × | √ |
微任务:
浏览器 | nodejs | |
---|---|---|
Process.nextTick | × | √ |
Promise | √ | √ |
MutationObserver | √ | × |