事件循环机制:
执行顺序: 主任务 => 微任务 => 宏任务
宏任务:定时器(setTimeout setInterval、requestAnimationFrame)、事件绑定、ajax回调函数、node的fs模块
微任务: promise.then、 async await 、process.nextTick、queueMicrotask
案例1
console.log('start');
setTimeout(() => {
console.log(333);
}); // 安排明天干的活
Promise.resolve('x').then(() => {
console.log(3);
}).then(() => {
console.log(4);
}).then(() => {
console.log(5); // 小任务无限的加 今天干完否则下不了班
//nodejs 有小任务限制,跳过直接到宏任务
})
console.log('end');
输出结果:
start => end => 3 => 4 => 5 =>333
解释:
一个微任务情况,依次执行完微任务
案例2
console.log('start');
setTimeout(() => {
console.log(333);
}); // 安排明天干的活
queueMicrotask(() => {
console.log(1);
queueMicrotask(() => {
console.log(2);
});
})
Promise.resolve('x').then(() => {
console.log(3);
}).then(() => {
console.log(4);
}).then(() => {
console.log(5); // 小任务无限的加 今天干完否则下不了班
//nodejs 有小任务限制,跳过直接到宏任务
})
console.log('end');
输出结果:
start => end =>1 => 3 => 2 => 4 => 5 => 333
解释
当有多个微任务执行的时候 ,是交替执行
案例3
console.log(1);
setTimeout(() => {