nextTick原理

571 阅读4分钟

首先呢我们先来了解一下js的运行机制.

js运行机制

js执行是单线程的,它是基于事件循环的。事件循环大致分以下几个步骤: 1.所有同步任何都在主线程上执行,形成一个执行栈(execution context stack)。 2.主线程之外,还存在一个“任务队列”(task queue).只要异步任务有了运行结果,就在“任务队列”之中放置一个事件。 3.一旦“执行栈”中的所有同步任务执行完毕,系统就会读取“任务队列”,看看里面有哪些事件。那么对应的异步任务,于是结束等待状态,进入执行栈,开始执行。 4.主线程不断重复上面的(3).

主线程的执行过程就是一个tick,而所有的异步结果都是通过“任务队列”来调度被调度。消息队列中存放的是一个个的任务(task)。task分为两大类,一个是macro task(宏任务)、macro task (微任务),并且每个marco task结束后,都要清空所有的micro task.在浏览器环境中,常见的macro task 有setTimeout,MessageChannel,postMessage,setImmediate,常见的micro task有MutationObsever 和Promise.then.

Vue中的nextTick在2.5+后有一个单独的文件。在src/core/util/next-tick.js,

import { noop } from 'shared/util'
import { handleError } from './error'
import { isIOS, isNative } from './env'

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 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
}

/**
 * Wrap a function so that if any code inside triggers state change,
 * the changes are queued using a (macro) task instead of a microtask.
 */
export function withMacroTask (fn: Function): Function {
  return fn._withTask || (fn._withTask = function () {
    useMacroTask = true
    const res = fn.apply(null, arguments)
    useMacroTask = false
    return res
  })
}

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
    })
  }
}

首先定义了一个callbacks,然后设置了一个状态pending,然后定义了microTimerFunc和macroTimerFunc,这两个根据浏览器的支持程度,然后做不同的处理。我们来看下macroTimerFunc,先判断当前运行环境支不支持setImmediate并且是浏览器原生支持的,那么macroTimerFunc内部实现呢就去调用setImmediate,否则就执行new MessageChannel实例,拿到port2,去调用port.postMessage,然后就会执行flushCallbacks,否则的话,macroTimerFunc就会降级为setTimeout(flushCallbacks,0)的方式。 然后看一下microtask方式的实现,如果原生浏览器支持promise,通过promise.then(flushCallbacks).如果不支持就直接降级为macrotask的实现。

next-tick.js对外暴露了2个函数,先来看nextTick,把传入的回调函数cb压入callbacks数组,最后一次性地根据useMacroTask条件执行macroTimerFunc或者是microTimerFunc,而它们都会在下一个tick执行flushCallbacks,flushCallbacks的逻辑也比较简单,对callbacks遍历,然后执行相应的回调函数。 这里使用callbacks而不是直接在nextTick中执行回调函数的原因是保证在同一个tick内多次执行nextTick,不会开启多个异步任务,而把这些异步任务都压成一个同步任务,在下一个tick执行完毕。

nextTick函数最后是当nextTick不传cb参数的时候,提供一个Promise化的调用,比如:nextTick().then(()=>{}) 当_resolve函数执行,就会跳到then的逻辑中。 next-tick.js还对外暴露了withMacroTask函数,它是对函数做一层包装,确保函数执行过程中对数据任意的修改,触发变化执行nextTick的时候强制走macroTimerFunc。比如对于一些DOM交互事件,如v-on绑定的事件回调函数的处理,会强制走macrotask。

我们了解到数据的变化到DOM的重新渲染是一个异步过程,发生在下一个tick.这就是我们在平时的开发过程中,比如从服务端接口去获取数据的时候,数据做了修改,而我们的某些方法又依赖数据修改后的DOM变化,所以我们就必须在nextTick后执行。 vue提供了2种调用nextTick的方式,一种是全局API vue.nextTick,一种是实例上的方法vm.$nextTick,无论我们使用哪一种,最后都是调用next-tick.js中实现的nextTick方法。