宏任务和微任务
-
宏任务
- 宏任务指将当前的任务挪至下一个任务列的最顶端执行
- setTimeOut
- setInterval
-
微任务
- 微任务将当前任务的内容挪至当前任务列的最底端执行
- Promise
-
先同步后异步
console.log("a");//同步
setTimeout(function(){
console.log("b");//宏任务
},0);
Promise.resolve().then(function(){
console.log("c");//微任务
})
console.log("d"); //同步
//a d c b
Promise.resolve().then(function(){
setTimeout(function(){
console.log("b");
},0)
})
setTimeout(function(){
Promise.resolve().then(function(){
console.log("a");
})
},0) //a b
Promise.resolve().then(function(){
setTimeout(function(){
console.log("c");
},0)
})
setTimeout(function(){
console.log("a");
},0)
setTimeout(function(){
console.log("b");
}); // a b c
var i=0;
fn();
function fn(){
fn1();
document.addEventListener("abc",function(){
console.log("d");
});
console.log("a");
fn2();
}
function fn1(){
console.log("b");
var evt=new Event("abc");
document.dispatchEvent(evt);
}
function fn2(){
console.log("c");
i++;
if(i<5) fn2();
} //完全同步
//先抛发后执行不能打印 ,所有不打印d.先执行后抛发可以打印
// b a c c c c c
-
微任务内的微任务优于微任务执行
new Promise(function(resolve){ resolve(); Promise.resolve().then(function(){ console.log("b"); }) Promise.resolve().then(function(){ console.log("c"); }) }).then(function(){ console.log("a"); }) //b c a
-
微任务大于宏任务执行
-
宏任务里的微任务比微任务里的宏任务优先
-
then里面的同步比then里面的promise优先
-
promise 从then开始才是微任务,否则为同步任务
new Promise(function (res) {
console.log(1);//---1 同步任务
res();
Promise.resolve().then(function () {
console.log(2);//---3 微任务
});
new Promise(function (res) {
res();
}).then(function () {
console.log(-1);//---4 后面的微任务
});
console.log(0);//-----2 同步任务
})
.then(function () {
console.log(3);//---5
Promise.resolve().then(function () {
console.log(4);//---7 微任务大于宏任务
});
})
.then(function () {
console.log(5);//---8
});
Promise.resolve().then(function () {
console.log(6);//---6 then里面的同步比then里面的promise优先
Promise.resolve().then(function () {
console.log(7);//----9
});
});
setTimeout(function () { //宏任务
setTimeout(function () {
console.log(8);//---12 宏任务中的宏任务
}, 0);
Promise.resolve().then(function () {
console.log(9);//---10 宏任务中的微任务
});
}, 0);
setTimeout(function () {
console.log(10);//---11
}, 0);
// 1 0 2 -1 3 6 4 5 7 9 10 8