Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

event loop #17

Open
WangXiZhu opened this issue Feb 26, 2017 · 0 comments
Open

event loop #17

WangXiZhu opened this issue Feb 26, 2017 · 0 comments

Comments

@WangXiZhu
Copy link
Owner

event-loop microtasks & macrotasks

在javascript中了解事件机制非常重要,它能帮我们更好清楚javascript本身。

了解了microtasksmacrotasks,javascript事件也大致清楚了。类别如下:

macrotasks

  • setTimeout
  • setInterval
  • setImmediate
  • I/O
  • UI rendering

microtasks

  • process.nextTick,
  • Promises,
  • Object.observe,
  • MutationObserver

在程序运行中表现有何异同呢?

console.log('script start');

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

Promise.resolve().then(function() {
  console.log('promise1');
}).then(function() {
  console.log('promise2');
});

console.log('script end');

例子中包含三部分:

  • 正常javascript程序
  • setTimeout->macrotasks
  • Promise->microtasks

运行结果如下:

script start
script end
promise1
promise2
setTimeout

规范中的microtasks和macrotasks

  • 一个事件循环(event loop)会有一个或多个任务队列(task queue) task queue 就是 macrotask queue
  • 每一个 event loop 都有一个 microtask queue
    task queue == macrotask queue != microtask queue
  • 一个任务 task 可以放入 macrotask queue 也可以放入 microtask queue 中
  • 当一个 task 被放入队列 queue(macro或micro) 那这个 task 就可以被立即执行了

在上面的理论基础上,分析如下

cycle1 :

  1. 整体代码加入到 js task中, 立即执行。打印 script start
  2. setTimeout,加入到 macrotask队列中(下一个执行队列),不打印
  3. Promise,加入 microtask中,但仍属于当前事件轮询中的任务
  4. script end正常打印

cycle2 :

  1. 整段代码结束,下面就执行 microtasks,打印 promise1, 当前js task中为 Promise回调, 返回值为 undefined,当前 microtask执行完毕。
  2. 遇到第二个 then,加入到 microtask中。执行下一个microtask(microtasks只有当前这个then callback),则打印promise2。目前整个任务完毕。继续执行下一个task(macrotask)
  3. setTimeout callback 作为一个新的task(macrotask),继续执行 ,打印 setTimeout

参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant