從vue的$nextTick看宏任務、微任務


1、nextTick調用方法

首先看nextTick的調用方法:

https://cn.vuejs.org/v2/api/#Vue-nextTick

復制代碼
// 修改數據
vm.msg = 'Hello'
// DOM 還沒有更新
Vue.nextTick(function () {
  // DOM 更新了
})

// 作為一個 Promise 使用 (2.1.0 起新增,詳見接下來的提示)
Vue.nextTick()
  .then(function () {
    // DOM 更新了
  })
復制代碼

即:既可以支持回調函數,也可以支持then方法(即Promise)。

 

2、vue nextTick源碼分析

https://github.com/vuejs/vue/blob/dev/src/core/util/next-tick.js

核心代碼--nextTick函數:

復制代碼
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
    })
  }
}
復制代碼

 

核心的代碼

復制代碼
if (!pending) {
    pending = true
    if (useMacroTask) {
      macroTimerFunc()
    } else {
      microTimerFunc()
    }
  }
復制代碼

即:nextTick既可以是宏任務,又可以是微任務

 

接着看微任務的定義:

復制代碼
// 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
}
復制代碼

即:vue環境支持Promis的話,使用Promise。否則microTimerFunc 被定義為宏任務macroTimerFunc

 

接着看macroTimerFunc的定義:

復制代碼
// 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)
  }
}
復制代碼

優先使用setImmediate(只有ie瀏覽器10以上支持),其次是MessageChannel,最后是setTimeout。以上三個都屬於宏任務。

 

HTML5中規定setTimeout的最小時間延遲是4ms,也就是說理想環境下異步回調最快也是4ms才能觸發。Vue使用這么多函數來模擬異步任務,其目的只有一個, 就是讓回調異步且盡早調用。而  MessageChannel 和  setImmediate 的延遲明顯是小於  setTimeout的。

 

 

$nextTick屬於宏任務還是微任務,你會了嗎?

 

 3、那什么時候使用宏任務,什么時候使用微任務呢?

在 Vue 2.4 之前都是使用的  microtasks(微任務),但是 microtasks 的優先級過高,在某些情況下可能會出現比事件冒泡更快的情況,但如果都使用  macrotasks(宏任務) 又可能會出現渲染的性能問題。所以 在新版本中,會默認使用 microtasks但在特殊情況下會使用 macrotasks。比如 v-on
下圖是使用v-on時,源碼調試截圖:

在chrome下使用了MessageChannel實現的宏任務。

 4、宏任務和微任務執行順序

復制代碼
for (macroTask of macroTaskQueue) {
    // 1. Handle current MACRO-TASK
    handleMacroTask();
      
    // 2. Handle all MICRO-TASK
    for (microTask of microTaskQueue) {
        handleMicroTask(microTask);
    }
}
復制代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM