Eventloop中的microtask和macrotask

Js Front End

EventLoop

js是单线程的, 所有异步都需要经过Eventloop(事件循环).这里不介绍eventloop

主要记录下eventloop中的microtask 和macrotask

microtask

  • process.nextTick
  • Promise
  • Object.observe
  • MutationObserver

macrotask

  • setTimeout
  • setImmediate
  • setInterval
  • MessageChannel
  • UI rendering
  • 网络I/O以及用户I/O
  • network

优先级

  • microtask > macrotask
  • process.nextTick > promise (process.nextTick只在node使用)
  • setTimeout和setImmediate在无IO操作下,两者执行顺序不确定,但是在IO操作下,setImmediate比setTimeout优先级高. 且setImmediate只在IE下有效

应用

Vue.nextTick源码中,分别使用了microtask和macrotask

在Vue2.4版本之前,默认都是使用microtask.优先判断是否支持promise,如果不支持则退回到MutationObserver,如果再不支持则回退到setTimeout

但在后续更新中,Vue已经修改nextTick实现方式.默认使用microtask, 同时也提供方法强制使用macrotask,例如由v-on绑定的事件处理.

原因就是因为microtask优先级太高.甚至高于事件冒泡. 而macrotask则会引起一些问题.

详情请看Vue.nextTick源码

// Here we have async deferring wrappers using both micro and macro tasks.
// In < 2.4 we used micro tasks everywhere, but there are some scenarios where
// micro tasks have too high a priority and fires in between supposedly
// sequential events (e.g. #4521, #6690) or even between bubbling of the same
// event (#6566). However, using macro tasks everywhere also has subtle problems
// when state is changed right before repaint (e.g. #6813, out-in transitions).
// Here we use micro task by default, but expose a way to force macro task when
// needed (e.g. in event handlers attached by v-on).
let microTimerFunc
let macroTimerFunc
let useMacroTask = false

// Determine (macro) Task defer implementation.
// Technically setImmediate should be the ideal choice, but it's only available
// in IE. The only polyfill that consistently queues the callback after all DOM
// events triggered in the same loop is by using MessageChannel.
/* istanbul ignore if */
if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
  macroTimerFunc = () => {
    setImmediate(flushCallbacks)
  }
} else if (
  typeof MessageChannel !== 'undefined' &&
  (isNative(MessageChannel) ||
    // PhantomJS
    MessageChannel.toString() === '[object MessageChannelConstructor]')
) {
  const channel = new MessageChannel()
  const port = channel.port2
  channel.port1.onmessage = flushCallbacks
  macroTimerFunc = () => {
    port.postMessage(1)
  }
} else {
  /* istanbul ignore next */
  macroTimerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }
}

// Determine MicroTask defer implementation.
/* istanbul ignore next, $flow-disable-line */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
  const p = Promise.resolve()
  microTimerFunc = () => {
    p.then(flushCallbacks)
    // in problematic UIWebViews, Promise.then doesn't completely break, but
    // it can get stuck in a weird state where callbacks are pushed into the
    // microtask queue but the queue isn't being flushed, until the browser
    // needs to do some other work, e.g. handle a timer. Therefore we can
    // "force" the microtask queue to be flushed by adding an empty timer.
    if (isIOS) setTimeout(noop)
  }
} else {
  // fallback to macro
  microTimerFunc = macroTimerFunc
}