源码用了flow做静态检查,这里去除flow部分
核心逻辑其实就两步:
- 保存回调函数
- 根据不同浏览器的情况选择不同的方法延迟执行回调函数
首先看函数nextTick
的实现:
const callbacks = []
let pending = false
let timerFunc
// cb: 回调函数
// ctx: 用于改变this指向
function nextTick (cb, ctx) {
let _resolve // 保存通过then传入的回调函数
callbacks.push(() => {
if (cb) {
try {
cb.call(ctx)
} catch (e) {
handleError(e, ctx, 'nextTick')
}
} else if (_resolve) {
_resolve(ctx)
}
})
if (!pending) {
pending = true
timerFunc()
}
// $flow-disable-line
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve
})
}
}
我们可以看到,源码在收集回调函数的时候分了两种情况:传入回调函数和不传回调函数。如果是传入回调函数的情况,则直接调用。如果没有传回调函数,就默认返回一个Promise,通过_resolve
保存then
传入的回调函数,将_resolve
的调用保存在数组中。
接着,通过pending
保证在同一作用域下nextTick
只调用一次。在这里调用timerFunc
延迟执行callbacks
里面的回调函数。
现在我们来看看timerFunc
的代码:
import { noop } from 'shared/util'
import { handleError } from './error'
import { isIE, isIOS, isNative } from './env'
// noop: 一个空函数
// isIE:是否是IE环境
// isIOS: 是否IOS环境
// isNative: 是否是浏览器等原生支持
let timerFunc
let isUsingMicroTask = false // 是否使用了微任务
// 在不同环境下选择不同方法延迟,首先选择微任务,
// 微任务不可以再利用宏任务
if (typeof Promise !== 'undefined' && isNative(Promise)) {
const p = Promise.resolve()
timerFunc = () => {
p.then(flushCallbacks)
// 如果是IOS环境,由于Promise.then可能会出现一些情况:
// 例如回调被推入微任务队列中,但是没有被执行,这时可
// 以通过做一些额外的操作强行刷新微任务队列。这里使用
// 一个空的计时器刷新微任务队列。
if (isIOS) setTimeout(noop)
}
isUsingMicroTask = true
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
let counter = 1
const observer = new MutationObserver(flushCallbacks)
const textNode = document.createTextNode(String(counter))
observer.observe(textNode, {
characterData: true
})
timerFunc = () => {
counter = (counter + 1) % 2
textNode.data = String(counter)
}
isUsingMicroTask = true
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
timerFunc = () => {
setImmediate(flushCallbacks)
}
} else {
timerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}
从上述代码看出,Vue
做延迟操作使用的API
优先级是:Promise
> MutationObserver
> setImmediate
> setTimeout
。其中前两个是微任务,后两个是宏任务。在延迟结束后,调用flushCallbacks
执行回调函数。flushCallbacks
代码如下:
function flushCallbacks () {
pending = false
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++) {
copies[i]()
}
}
从中看出,这个函数就是循环调用了回调函数然后初始化callbacks
和pending
而已。
最后梳理一下代码执行逻辑:
- 判断执行环境,选择合适的
API
做延迟处理,选择标准是微任务优先于宏任务。将操作封装在timerFunc
函数中。 - 收集回调函数,判断是否显式的传入了回调函数,如果是则直接保存这个回调函数的调用到
callbacks
,如果不是则返回一个Promise
,通过_resolve
保存then
传入的回调函数。 - 执行
timerFunc
函数,通过pending
保证同一作用域多次调用nextTick
时只触发一次。延迟结束后执行callbacks
中的回调函数并初始化callbacks
和pending
。
完整源码如下:
/* @flow */
/* globals MutationObserver */
import { noop } from 'shared/util'
import { handleError } from './error'
import { isIE, isIOS, isNative } from './env'
export let isUsingMicroTask = false
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 microtasks.
// In 2.5 we used (macro) tasks (in combination with microtasks).
// However, it has subtle problems when state is changed right before repaint
// (e.g. #6813, out-in transitions).
// Also, using (macro) tasks in event handler would cause some weird behaviors
// that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).
// So we now use microtasks everywhere, again.
// A major drawback of this tradeoff is that there are some scenarios
// where microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690, which have workarounds)
// or even between bubbling of the same event (#6566).
let timerFunc
// The nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore next, $flow-disable-line */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
const p = Promise.resolve()
timerFunc = () => {
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)
}
isUsingMicroTask = true
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
// PhantomJS and iOS 7.x
MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
// Use MutationObserver where native Promise is not available,
// e.g. PhantomJS, iOS7, Android 4.4
// (#6466 MutationObserver is unreliable in IE11)
let counter = 1
const observer = new MutationObserver(flushCallbacks)
const textNode = document.createTextNode(String(counter))
observer.observe(textNode, {
characterData: true
})
timerFunc = () => {
counter = (counter + 1) % 2
textNode.data = String(counter)
}
isUsingMicroTask = true
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
// Fallback to setImmediate.
// Technically it leverages the (macro) task queue,
// but it is still a better choice than setTimeout.
timerFunc = () => {
setImmediate(flushCallbacks)
}
} else {
// Fallback to setTimeout.
timerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}
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
timerFunc()
}
// $flow-disable-line
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve
})
}
}
以上。