zoukankan      html  css  js  c++  java
  • 宏事件,微事件的执行

    // JS主任务(宏任务1)开始,输出1.Start
    console.log('1.Start')
    // setTimeout为宏任务(2),加入宏任务事件循环
    setTimeout(function() {
        console.log('2.Timer is on');
    });
    
    new Promise((resolve, reject) => {
        // Promise构造函数参数会立即执行, 输出3.For loop is on
        console.log('3.For loop is on');
        for (let i = 0; i < 2; i++) {
            if (i == 1) {
            // 满足条件,输出4.resolved
            console.log('4.resolved');
            // 触发resolved(即then回调),为微事件,加入微事件循环
            resolve();
            }
        // resolve之后代码会继续执行,输出1,
        // 所以最好resolve之后显式使用return
        console.log(i);
        }
    }).then(function(val) {
        console.log('5.Function then is on');
    });
    
    // 宏事件1,输出6.End
    console.log('6.End');
    // 主JS执行完毕(宏事件1执行完毕)
    
    // 每一个宏事件完成之后,都会依次取出所有微事件并执行(这里只有then在微事件循环中)
    // 执行then回调,输出5.Function then is on
    
    // 微事件全部完成后,从宏事件队列中取出下一个宏事件执行(这里只有setTimeout在宏事件中)
    // 执行setTimeout回调,输出2.Timer is on
    
    // 完整输出如下:
    // 1.Start
    // 3.For loop is on
    // 0
    // 4.resolved
    // 1
    // 6.End
    // 5.Function then is on
    // 2.Timer is on
    

    process.nextTick(callback)类似node.js版的"setTimeout",但会开启一个微任务,在宏事件事件循环的下一次循环前调用 callback 回调函数。

    一道练习题

    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);
        });
    });
    
    process.nextTick(function() {
        console.log(6);
    });
    
    new Promise(function(resolve) {
        console.log(7);
        resolve();
    }).then(function() {
        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);
        });
    });
    
    // 完整输出
    // 1
    // 7
    // 6
    // 8
    // 2
    // 4
    // 3
    // 5
    // 9
    // 11
    // 10
    // 12
    

    参考网址:这一次,彻底弄懂 JavaScript 执行机制

  • 相关阅读:
    Randomization Tests
    关于Spring中的<context:annotationconfig/>配置
    PUT method support
    在对话框picture control中利用opengl进行绘图
    【学习笔记】《卓有成效的管理者》 第三章 我能贡献什么
    程序员的黄金时代
    nginx webdav配置
    iphone4s 如何强制关机
    并查集
    实战虚拟化存储设计之三MultiPathing
  • 原文地址:https://www.cnblogs.com/hycstar/p/14354863.html
Copyright © 2011-2022 走看看