事件循环与nextTick

914 阅读4分钟

事件循环

浏览器中的事件循环

javascript 代码执行过程中,除了依靠函数调用栈来处理函数的执行顺序,还依靠任务队列(task queue)来处理另外一些代码的执行。整个执行过程我们称为事件循环过程。一个线程中事件循环是唯一的,但是任务队列可以拥有多个。任务队列又分为macro-task(宏任务)与micro-task(微任务)

macro-task 大概包括:

  • script
  • setTimeout
  • setInterval
  • setImmediate
  • I/O
  • UI render

micro-task大概包括:

  • process.nextTick
  • Promise
  • MutationObserver

事件循环,宏任务,微任务之间的关系

事件循环.jpg

总的结论是,执行宏任务,然后执行该宏任务产生的微任务,若微任务在执行过程中产生了新的微任务,则继续执行微任务,微任务执行完毕后,再回到宏任务中进行下一轮。

async function async1(){
    await async2()
    console.log('async1 end')
 }
 
 async function async2(){
   console.log('async2 end')
 }
 
 async1()
 
 setTimeout(function(){
   console.log('setTimeout')
 },0)
 
 new Promise(resolve=>{
    console.log('Promise')
    resolve()
 })
 .then(function(){
   console.log('promise1')
 })
 .then(function(){
   console.log('promise2')
 })

宏任务微任务
setTimeoutasync1 end
promise1
promise2

结合流程图,答案输出为:async2 end => Promise => async1 end => promise1 => promise2 => setTimeout

Vue 中的 $nextTick

Vue 官方对 nextTick 这个API 的描述:

在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的DOM

<template>
  <div id="app">
    <div  ref='foo'>
        {{foo}}
    </div>   
    <button @click="changeFoo">改变foo</button>
  </div>
</template>

<script>
export default {
  data(){
      return{
          foo:'ready'
      }
  },

  methods:{
     changeFoo(){
       this.foo='1'
       console.log('foo ',this.foo,this.$refs['foo'].innerHTML) //打出来的Html还是ready , 但foo已经变成了1
        this.$nextTick(()=>{
         console.log('foo in NextTick',this.foo,this.$refs['foo'].innerHTML)//可以打印出 innerHTML为1
       })
     }

  }
}
</script>

<style>

</style>

可能你还没有注意到,Vue 异步执行 DOM 更新。只要观察到数据变化,Vue将开启一个队列,并缓冲在同一事件循环中发生的所有数据改变。如果同一个 watcher 被多次触发,只会被推入到队列中一次。这种在缓冲是去除重复数据对于避免不必要的计算合 DOM 操作上非常重要。然后,在下一个的事件循环 "tick"中,Vue刷新队列并执行实际(已去重的)工作。Vue在内部尝试对异步队列使用原生的 Promise.then 和 MessageChannel,如果执行环境不支持,会采用 setTimeout(fn,0)代替

例如,当你设置 vm.someData = 'new value' ,该组件不会立即重新渲染。当刷新队列时,组件会在事件循环队列清空时的下一个“tick”更新。多数情况我们不需要关心这个过程,但是如果你想在 DOM 状态更新后做点什么,这就可能会有些棘手。虽然 Vue.js 通常鼓励开发人员沿着“数据驱动”的方式思考,避免直接接触 DOM,但是有时我们确实要这么做。为了在数据变化之后等待 Vue 完成更新 DOM ,可以在数据变化之后立即使用 Vue.nextTick(callback) 。这样回调函数在 DOM 更新完成后就会调用。

nextTick 源码浅析

watcher

src\core\observer\watcher.js

// 用来标记 watcher
let uid = 0

**
 * 
 * @param {*} options watcher 的配置项
 */
export default class Watcher {
  vm: Component;
  expression: string;
  cb: Function;
  id: number;
  deep: boolean;
  user: boolean;
  lazy: boolean;
  sync: boolean;
  dirty: boolean;
  active: boolean;
  deps: Array<Dep>;
  newDeps: Array<Dep>;
  depIds: SimpleSet;
  newDepIds: SimpleSet;
  before: ?Function;
  getter: Function;
  value: any;

  constructor (
    vm: Component,
    expOrFn: string | Function,
    cb: Function,
    options?: ?Object,
    isRenderWatcher?: boolean
  ) {    
    this.vm = vm
    if (isRenderWatcher) {
      vm._watcher = this
    }
    vm._watchers.push(this)
  

    this.id = ++uid // uid for batching


    // parse expression for getter
    if (typeof expOrFn === 'function') {
      this.getter = expOrFn
    } 

watcher.update

src\core\observer\watcher.js

/**
 * 响应式数据更新时,dep 通知 watcher 执行 update 方法,
 * dep.notify()之后watcher执⾏更新,执⾏⼊队操作
 */
update () {
    /* istanbul ignore else */
    // computed
    if (this.lazy) {
      this.dirty = true
    } else if (this.sync) {
      this.run()
    } else {
      // 入队
      queueWatcher(this)
    }
  }

异步更新队列 queueWatcher(watcher)

core\observer\scheduler.js

export function queueWatcher (watcher: Watcher) {
  const id = watcher.id
  // 去重
  if (has[id] == null) {
    has[id] = true
    if (!flushing) {
      // 入队
      queue.push(watcher)
    } else {
      // if already flushing, splice the watcher based on its id
      // if already past its id, it will be run next immediately.
      let i = queue.length - 1
      while (i > index && queue[i].id > watcher.id) {
        i--
      }
      queue.splice(i + 1, 0, watcher)
    }
    // queue the flush
    if (!waiting) {
      waiting = true
      // 将flushSchedulerQueue以异步方式加入队列
      nextTick(flushSchedulerQueue)
    }
  }
}


function flushSchedulerQueue () {
  //...
  let watcher, id
  for (index = 0; index < queue.length; index++) {
    // 每次拿出一个watcher
    watcher = queue[index]
    id = watcher.id
    has[id] = null
    // 真正的操作是run方法做的
    watcher.run()
  }
  //...

}

nextTick(flushSchedulerQueue)

src\core\util\next-tick.js nextTick按照特定异步策略执⾏队列操作


/**
 * 异步更新队列
 */
 
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]()
  }
}
//根据环境定义timerFunc,优先采用微任务
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)
  }
}


// 将cb函数放入回调队列队尾
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
    })
  }
}

小结

  • 异步:只要侦听到数据变化,Vue 将开启⼀个队列,并缓冲在同⼀事件循环中发⽣的所有数据变更。
  • 批量:如果同⼀个 watcher 被多次触发,只会被推⼊到队列中⼀次。去重对于避免不必要的计算和 DOM 操作是⾮常重要的。然后,在下⼀个的事件循环“tick”中,Vue 刷新队列执⾏实际⼯作。
  • 异步策略:Vue 在内部对异步队列尝试使⽤原⽣的 Promise.then、MutationObserver 或setImmediate,如果执⾏环境都不⽀持,则会采⽤ setTimeout 代替。

nextTick.jpg