在下次 DOM 更新循環結束以後執行延遲迴調。在修改數據以後當即使用這個方法,獲取更新後的 DOM。javascript
怎麼實現的延遲迴調html
vue 大多數狀況下優先使用微任務, 不多的地方使用宏任務vue
if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
macroTimerFunc = () => {
setImmediate(flushCallbacks)
}
}
複製代碼
setImmediate 瀏覽器支持狀況 java
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)
}
}
複製代碼
MessageChannel 瀏覽器支持狀況 ios
else {
/* istanbul ignore next */
macroTimerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}
複製代碼
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)
}
}
複製代碼
Promise 瀏覽器支持狀況 瀏覽器
else {
// fallback to macro
microTimerFunc = macroTimerFunc
}
複製代碼
從源碼中能夠看出,在DOM事件中使用Vue.nextTick 默認使用宏任務, 其餘地方使用Vue.nextTick默認使用微任務。app
其實從源碼中註釋中能夠看出Vue最開始都是使用微任務方式,後面出現了bug,才引入了宏任務方式異步
// 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).
複製代碼
產考資料: JavaScript 運行機制詳解:再談Event Loopasync