美文网首页
event loop 机制

event loop 机制

作者: 神刀 | 来源:发表于2017-12-31 16:01 被阅读6次

    基本概念:
    大家更熟悉的关于事件循环的机制说法大概是:主进程执行完了之后,每次从任务队列里取一个任务执行。但是promise出现之后,这个说法就不太准确了。

    事实上引擎会把我们的所有任务分类,一部分归为macroTask,另外一部分归为microTack,引擎对这两种队列有不同的处理。下面是类别划分:

    macroTask: setTimeout,
    setInterval,
    setImmediate,
    requestAnimationFrame,
    I/O,
    UI rendering

    microTask: process.nextTick,
    Promise,
    Object.observe,
    MutationObserver

    例子:
    function a(){
    console.log('main1');
    process.nextTick(function() {console.log('process.nextTick1')});

    setTimeout(function() {
    console.log('setTimeout');
    process.nextTick(function() {console.log('process.nextTick2')});
    }, 0);

    new Promise(function(resolve, reject) {
    console.log('promise’); resolve();
    }).then(function() { console.log('promise then');
    });
    console.log('main2');
    }

    执行结果:
    main1
    promise
    main2
    process.nextTick1
    promise then
    setTimeout
    process.nextTick2

    原理图示:
    注: 1. 主进程的代码属于macroTask
    2. 在处理了macroTask和microTask之后,会进行一次Update the rendering

    相关文章

      网友评论

          本文标题:event loop 机制

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