美文网首页
JS中的事件循环

JS中的事件循环

作者: 真是个非常帅气的昵称呢 | 来源:发表于2021-05-12 21:01 被阅读0次
        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的回调在重绘之前执行,没有确定的时间,何时重绘由浏览器决定

    相关文章

      网友评论

          本文标题:JS中的事件循环

          本文链接:https://www.haomeiwen.com/subject/yiowzhtx.html