nextTick

Vue 里将next-tick.js独立成一单独的文件,主要向外暴露了两个函数nextTickwithMacroTask

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
    })
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

调用nextTick(cb)就是让函数cb在下一个tick里执行。

pending标志着是否正在执行callbacks里的函数。

nextTick执行过程为:

  1. 新建一函数,并推入到callbacks队列里,等待之后执行该函数。
  2. 检测pending,决定是否执行callbacks里的函数
    • pendingtrue:说明正在执行callbacks,则忽略,进入下一步;
    • pendingfalse:说明没有执行callbacks
      • 则将pending置为true
      • 根据useMacroTask的取值,决定用macroTimerFuncmicroTimerFunc来执行callbacks里的函数
  3. cb不存在并且环境里支持 Promise,则返回一 Promise 实例,当调用_resolve时,该实例的状态变为resolved

可以看到,当cb存在时,加入到callbacks里的函数在执行时,就是执行cb

nextTick().then(() => {
  console.log('cb 为空时,在下一个 tick,这里会执行')
})
1
2
3

但是在cb为空时,若是环境支持 Promise,nextTick将返回一 Promise 实例,等到下一个tick的时候,Promise 实例会改变为resolved状态,从而通过 Promise 实例的then方法添加的函数就可以成功执行。

TODO: 这里有个疑问,若是环境不支持 Promise,nextTick将返回undefined,给nextTick上调用then方法,会报错吧?

macroTimerFunc / microTimerFunc

上面的第二步里,会根据useMacroTask的取值,决定用macroTimerFuncmicroTimerFunc来执行callbacks里的函数。我们先来看看这两个函数的区别。

// 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
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

这里会根据环境来决定macroTimerFuncmicroTimerFunc采取哪一种实现。

macroTimerFunc的实现选取顺序为:

microTimerFunc实现的选取顺序为:

  • Promise
  • macroTimerFunc

若是环境支持 Promise,则使用 Promise 实现microTimerFunc,否则就使用上面确定的macroTimerFunc

flushCallbacks

无论是使用macroTimerFunc还是macroTimerFunc,最终都是在下一次tick里执行了flushCallbacks。该函数就是将callbacks数组里函数取出,并一一执行。

function flushCallbacks () {
  pending = false
  const copies = callbacks.slice(0)
  callbacks.length = 0
  for (let i = 0; i < copies.length; i++) {
    copies[i]()
  }
}
1
2
3
4
5
6
7
8

withMacroTask

withMacroTask是将fn函数封装一层,分装的作用是:在fn函数内若是调用了nextTick(cb),则传入nextTick的函数cb将强制使用macroTimerFunc来执行,即放在 macro task 队列里执行。

这种用法主要用于封装监听 DOM 事件的方法,以便在 DOM 事件内发生的状态变更引起渲染 Watcher 重新计算时使用到的nextTickmacroTimerFunc里执行,详见事件监听器 - 原生事件模块。如果不这么做的话,可能引起的问题有:#6566open in new window,还有其他问题可以见上面的注释。

export function withMacroTask (fn: Function): Function {
  return fn._withTask || (fn._withTask = function () {
    useMacroTask = true
    const res = fn.apply(null, arguments)
    useMacroTask = false
    return res
  })
}
1
2
3
4
5
6
7
8

Vue.nextTick / vm.$nextTick

Vue 有两种方式将nextTick暴露出去,分别是静态方法Vue.nextTick和实例方法vm.$nextTick,它们都是间接地调用了nextTick函数。

// src/core/global-api/index.js
import { nextTick } from '../util/index'
export function initGlobalAPI (Vue: GlobalAPI) {
  // ...
  Vue.nextTick = nextTick
}
1
2
3
4
5
6
// src/core/instance/render.js
export function renderMixin (Vue: Class<Component>) {
  // ...
  Vue.prototype.$nextTick = function (fn: Function) {
    return nextTick(fn, this)
  }
}
1
2
3
4
5
6
7

释疑

为什么不在 nextTick 里直接执行 cb,而要先压入 callbacks 里?

一开始读nextTick的源码,就好奇,为什么不在nextTick里直接执行cb,而是先把cb加入到callbacks数组里,再统一执行呢?

假设在主线程执行时,我们要执行 10 次nextTick(cb),且假设nextTick是用setTimeout实现的。这样的话,执行 10 次nextTick,将产生 10 个setTimeout定时器;但是要是把 10 个cb放在callbacks里,只会产生一个setTimeout定时器,且在当前主线程中,可以任意调用nextTick(cb)加入新的cb,所有的这些cb都会在下一次tick时顺序执行。如此,也算是提升了一些性能。