js 事件循环
JavaScript 是一门单线程语言,单线程意味同一时间只能做一件事,这样没有造成堵塞就是因为事件循环。
在javascript中所有任务可以分为同步任务,异步任务。
同步任务:立即执行的任务,一般按照执行顺序直接进入主线程执行
异步任务: 异步执行的任务,比如setTimeout,ajax请求等。
当执行一段代码时,会将同步代码按顺序排在执行栈中;然后依次执行里面的函数;将遇到异步任务时会放入任务队列中,每个任务关联一个回调函数,等主线程任务全部执行完毕,会去任务队列取出已完成的异步任务回调推入执行栈,上述过程不断重复就是事件循环。

异步任务又可分为微任务和宏任务
常见微任务:
- promise.then()、promise.catch()
- new MutaionObserver()
- process.nextTick()
常见宏任务:
- setTimeout()
- setInterval()
- setImmediate()
- postMessae
事件循环的过程中,微任务执行在在执行栈全部执行完毕之后,任务队列之前。
async function async1() {
console.log("1");
await async2();
console.log("2"); //微任务
}
async function async2() {
console.log("3");
}
console.log("4");
setTimeout(function () {
console.log("5"); //宏任务
}, 1000);
async1();
new Promise(function (resolve) {
console.log("6");
resolve();
}).then(function () {
// 微任务
console.log("7");
});
上面的输出顺序:
1.按照从上到下顺序,首先执行同步 console.log("4");输出4
2.执行async1();输出1
3. .执行async2();输出3,await 后面代码是微任务
4. 执行Promise,输出6,.then为微任务
5.同步执行完,按照顺序执行微任务 输出2 ,7
6.微任务执行完,执行宏任务,输出5

浙公网安备 33010602011771号