JS中的事件循环

    console.log('start');
    setTimeout(() => {
      console.log('children2');
      Promise.resolve().then(() => {
        console.log('children3');
      })
    }, 0);

    new Promise(function (resolve, reject) {
      console.log('children4');
      setTimeout(function () {
        console.log('children5');
        resolve('children6')
      }, 0)
    }).then((res) => {
      console.log('children7');
      setTimeout(() => {
        console.log(res);
      }, 0)
    })
//输出
//start 4 2 3 5 7 6

宏任务

包括:包含执行整体的js代码,事件回调,XHR回调,定时器(setTimeout/setInterval/setImmediate),IO操作,UI render

微任务

包括:更新应用程序状态的任务,包括promise回调,MutationObserver,process.nextTick,Object.observe

image.png

事件循环的步骤
1.执行宏任务队列中的一个任务
2.执行微任务队列中的所有任务
3.UI render

setTimeout(function() {console.log('timer1')}, 0)

requestAnimationFrame(function(){
    console.log('requestAnimationFrame')
})

setTimeout(function() {console.log('timer2')}, 0)

new Promise(function executor(resolve) {
    console.log('promise 1')
    resolve()
    console.log('promise 2')
}).then(function() {
    console.log('promise then')
})

console.log('end')
//输出1  : promise1,promise2,end,promise then,requestAnimationFrame,timer1,timer2
//输出2  : promise1,promise2,end,promise then,timer1,timer2,requestAnimationFrame

浏览器只保证requestAnimationFrame的回调在重绘之前执行,没有确定的时间,何时重绘由浏览器决定
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容