1、js是单线程语言,其事件分为:同步任务和异步任务,异步任务分为宏任务与微任务;
2、执行顺序为:同步任务(主流程任务) ---> 微任务 ----> 宏任务
先执行同步任务,遇到异步任务则放入任务队列中,等同步任务执行完毕,执行任务队列中的微任务,再执行宏任务...
主线程从"任务队列"中读取事件,这个过程是循环不断的,所以整个的这种运行机制又称为Event Loop(事件循环)。
3、微任务主要包含:promise.then(fn) fn即会推入微任务队列
宏任务主要包含: setTimeout(fn1,time) fn1即会推入宏任务队列
4、执行顺序例子:
setTimeout(() => { console.log('timer1'); setTimeout(() => { console.log('timer3') }, 0) }, 0) setTimeout(() => { console.log('timer2') }, 0) console.log('start') //start\1\2\3
setTimeout(() => { console.log('timer1'); Promise.resolve().then(() => { console.log('promise') }) }, 0) setTimeout(() => { console.log('timer2') }, 0) console.log('start') //start\1\promise\2
Promise.resolve().then(() => { console.log('promise1'); const timer2 = setTimeout(() => { console.log('timer2') }, 0) }); const timer1 = setTimeout(() => { console.log('timer1') Promise.resolve().then(() => { console.log('promise2') }) }, 0) console.log('start'); //start/p1/t1/p2/t2
const promise1 = new Promise((resolve, reject) => { console.log(1); setTimeout(() => { console.log("timerStart"); resolve("success"); console.log("timerEnd"); }, 0); console.log(2); }); promise.then((res) => { console.log(res); }); console.log(4); //1 //2 //3 //4 //success //timerStart //timerEnd
标签:resolve,console,log,EventLoop,js,start,任务,循环,setTimeout From: https://www.cnblogs.com/ducky-L/p/17326495.html