nextTick原理及实现过程

  • Post author:
  • Post category:其他





next-tick源码

作用:将回调延迟到下次DOM更新周期之后执行。

下次DOM更新周期:其实是下次微任务执行时更新DOM。而vm.$nextTick是将回调添加到微任务中。



原理

  1. 先定义了一个callbacks存放所有的nextTick里的回调函数
  2. 然后判断一下当前的浏览器内核是否支持Promise,支持就用Promise来触发回调函数
  3. 如果不支持Promise,再判断是否支持MutationObserver(一个可以监听DOM结构变化的接口,观察文本节点发生变化时,触发执行所有回调函数)
  4. 如果不支持MutationObserver,再判断是否支持setImmediate
  5. 如果以上都不支持就只能用setTimeout来完成异步执行了

    延迟调用优先级如下:Promise > MutationObserver > setImmediate > setTimeout



nextTick里的宏任务和微任务

关于宏任务,vue先判断是否支持setImmediate,是就使用setImmediate;不是就只能用setTimeout。

关于微任务,vue会先判断是否支持promise,是就使用promise,然后判断是否支持MutationObserver,是就使用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 // 每当向任务队列中插入任务时,将pending设置为true
  const copies = callbacks.slice(0)
  callbacks.length = 0
  for (let i = 0; i < copies.length; i++) {
    copies[i]()
  }
}

// 在2.5中,使用了(宏)任务(与微任务结合使用)
let timerFunc

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
  // 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.
  // 它利用了(宏)任务队列,但它仍然是比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')
      }
    }
    // 如果在支持Promise的环境中没有提供回调,则返回一个promise
    // 可以这样使用:this.$nextTick().then(() => {...})
    else if (_resolve) {
      _resolve(ctx)
    }
  })
  if (!pending) {
    // 每当向任务队列中插入任务时,将pending设置为true
    pending = true
    timerFunc()
  }
  // 在callbacks中添加一个函数,当这个函数执行时,执行Promise的resolve
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}



版权声明:本文为kiscon原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。