解讀vue源碼之nextTick:何謂 event-loop, 瀏覽器的事件機制,task/microtasks

前言:
前幾周在研究Vue的源碼,感覺設計得還是蠻精巧的。這裏主要談談其異步更新的機制,及實現nextTick的幾種方式,接着會擴展一些瀏覽器的event-loop的實現機制。
目錄:

nextTick 與異步渲染UI

vue中,data的改變是同步的,reactive的,但ui的渲染是異步,正如nextTick 一樣,都是在下一個tick去執行。
這篇文章講得比較細,但可能用的是老版本的vue了,只涉及到了MutationObserver 和 setTimeout。
Vue nextTick 源碼解讀

這裏的vue版本是2.5.17-beta.0。大致有以下幾個要點:

  • flushCallbacks 用來清空回調隊列和依次執行回調。
  • 定義了兩個timerFunc, microTimerFunc用於執行微任務microtasks,macroTimerFunc 用於執行任務tasks。
  • 放棄了MutationObserver,用setImmediate -> setImmdiate的polyfill MessageChannel -> setTimeout(fn, 0) 來構造 macroTimerFunc
  • 用 Promise.resolve().then(flushCallbacks) 來構造microTimerFunc, 若沒有原生支持的Promise, 則microTimerFunc 退化爲 macroTimerFunc
  • 默認使用 microtask 但暴露了強制使用task 的方法,如v-on綁定的事件handler
  • nextTick中接受一個cb 函數,和一個上下文對象ctx,主要做了兩件事
    • 把cb壓入回調隊列
    • 如果沒有正在執行任務(任務隊列是空的),則使用 macroTimerFunc()/ microTimerFunc() 執行flushCallbacks 清空隊列。

附源代碼:core/util/next-tick.js


/* @flow */
/* globals MessageChannel */

import { noop } from 'shared/util'
import { handleError } from './error'
import { isIOS, isNative } from './env'

const callbacks = []
let pending = false

function flushCallbacks () {
  pending = false
  const copies = callbacks.slice(0)
  callbacks.length = 0
  for (let i = 0; i < copies.length; i++) {
    copies[i]()
  }
}

// Here we have async deferring wrappers using both microtasks and (macro) tasks.
// In < 2.4 we used microtasks everywhere, but there are some scenarios where
// microtasks have too high a priority and fire 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 microtask 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
}

/**
 * Wrap a function so that if any code inside triggers state change,
 * the changes are queued using a (macro) task instead of a microtask.
 */
export function withMacroTask (fn: Function): Function {
  return fn._withTask || (fn._withTask = function () {
    useMacroTask = true
    const res = fn.apply(null, arguments)
    useMacroTask = false
    return res
  })
}

export function nextTick (cb?: Function, ctx?: Object) {
  let _resolve
  callbacks.push(() => {
    if (cb) {
      try {
        cb.call(ctx)
      } catch (e) {
        handleError(e, ctx, 'nextTick')
      }
    } else if (_resolve) {
      _resolve(ctx)
    }
  })
  if (!pending) {
    pending = true
    if (useMacroTask) {
      macroTimerFunc()
    } else {
      microTimerFunc()
    }
  }
  // $flow-disable-line
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}

瀏覽器的event-loop

主要參見這篇文章:Tasks, microtasks, queues and schedules

猜猜這段代碼的輸出結果?

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');

一個正確實現了 Ecmascript 的瀏覽器的輸出結果是:

script start, script end, promise1, promise2, setTimeout。

這與瀏覽器的event loop實現機制有關係。

瀏覽器中,每個線程都維護着自己的event loop 。所有同一來源的窗口都共享一個event loop 從而可以同步地通信。

一個事件循環有多個任務來源,在循環內部會確保任務的執行順序。但瀏覽器要在每個循環執行完後從任務來源中挑選一個來執行任務。瀏覽器優先執行性能敏感的任務,如I/O輸入。

任務(tasks)被作了日程安排(scheduled)。在任務之間,瀏覽器也許會 更新渲染。

setTimout 會等待一會兒,再爲它的回調安排一個新任務。

微任務(microtasks)會把事務安排在當前執行的代碼後立即做。如執行一個異步,但不需要重啓一個全新的任務。微任務隊列會放在沒有別的js在執行後做,即每個task的末位。新加入的microtask會被排在當前的微任務隊列中。微任務包括mutation observer 的回調和promises。微任務總是在下一個任務執行前完成。

某些瀏覽器的版本,如safari 和 firefox 40, 微軟的Edge 把promise當做任務來處理了。這會造成性能損失。

儘管我們正處於任務之中,只要JS的堆棧空了,微任務就會被放到回調後處理。
微任務在事件Listener的回調之間運行。但不會打擾正在執行的js。

微任務隊列和schedules中還給了一個瀏覽器中點擊事件的例子,值得一提的是,手動點擊和用.click()來模擬的結果是不一樣的。因爲.click()會讓同步分發事件。

總結:

  • 任務按次序執行,瀏覽器的dom渲染髮生在任務之間。
  • 微任務按次序執行,並且
    • 在每個回調後執行,只要沒有別的js正在執行則執行
    • 在每個任務的末尾執行。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章