zoukankan      html  css  js  c++  java
  • 事件循环执行顺序

    //主线程直接执行
    console.log('1');
    //丢到宏事件队列中
    setTimeout(function() {
        console.log('2');
        process.nextTick(function() {
            console.log('3');
        })
        new Promise(function(resolve) {
            console.log('4');
            resolve();
        }).then(function() {
            console.log('5')
        })
    })
    //微事件1
    process.nextTick(function() {
        console.log('6');
    })
    //主线程直接执行
    new Promise(function(resolve) {
        console.log('7');
        resolve();
    }).then(function() {
        //微事件2
        console.log('8')
    })
    //丢到宏事件队列中
    setTimeout(function() {
        console.log('9');
        process.nextTick(function() {
            console.log('10');
        })
        new Promise(function(resolve) {
            console.log('11');
            resolve();
        }).then(function() {
            console.log('12')
        })
    })
    首先浏览器执行js进入第一个宏任务进入主线程, 直接打印console.log('1')
    
    • 遇到 setTimeout  分发到宏任务Event Queue中
    
    • 遇到 process.nextTick 丢到微任务Event Queue中
    
    • 遇到 Promise, new Promise 直接执行 输出 console.log('7');
    
    • 执行then 被分发到微任务Event Queue中
    
    •第一轮宏任务执行结束,开始执行微任务 打印 6,8
    
    •第一轮微任务执行完毕,执行第二轮宏事件,执行setTimeout
    
    •先执行主线程宏任务,在执行微任务,打印'2,4,3,5'
    
    •在执行第二个setTimeout,同理打印 ‘9,11,10,12’
    
    •整段代码,共进行了三次事件循环,完整的输出为1,7,6,8,2,4,3,5,9,11,10,12。
    
  • 相关阅读:
    数据库的读读事务也会产生死锁
    数据库中的two phase locking
    排序合并连接(sort merge join)的原理
    SQL Server2016 原生支持JSON
    公司内部培训SQL Server传统索引结构PPT分享
    postgresql的ALTER经常使用操作
    POJ 1458 Common Subsequence(最长公共子序列LCS)
    Docker 1.3 公布
    spring bean之间的关系:继承;依赖
    hdu 1215 七夕节
  • 原文地址:https://www.cnblogs.com/shiyunfront/p/13095128.html
Copyright © 2011-2022 走看看