JS运行机制

JS 执行是单线程的,它是基于事件循环的。事件循环大致分为以下几个步骤:

  1. 所有同步任务都在主线程上执行,形成一个执行栈
  2. 主线程之外还存在一个“任务队列”。只要异步任务有了运行结果就在“任务队列”之中放置一个事件
  3. 一旦执行栈中所有同步任务执行完毕,系统就会读取“任务队列”,看看里面有哪些事件。那些对应的异步任务于是结束等待状态进入执行栈开始执行
  4. 主线程不断重复上面第三步

image.png
主线程·的执行过程就是一个tick,而所有的异步结果都是通过“任务队列”来调度
消息队列中存放的是一个个的任务(task),规范中规定task分为两大类

  • macro task
  • micro task

每个macro task结束后都要清空所有的micro task
在浏览器环境中,常见的 macro task 有 setTimeout、MessageChannel、postMessage、setImmediate;常见的 micro task 有 MutationObsever 和 Promise.then

nextTick在Vue中的实现

定义在src/core/util/next-tick.js中

  1. import { noop } from 'shared/util'
  2. import { handleError } from './error'
  3. import { isIE, isIOS, isNative } from './env'
  4. export let isUsingMicroTask = false
  5. const callbacks = []
  6. let pending = false
  7. // 对callbacks遍历,然后执行相应的回调函数
  8. function flushCallbacks () {
  9. pending = false
  10. const copies = callbacks.slice(0)
  11. callbacks.length = 0
  12. for (let i = 0; i < copies.length; i++) {
  13. copies[i]()
  14. }
  15. }
  16. // Here we have async deferring wrappers using microtasks.
  17. // In 2.5 we used (macro) tasks (in combination with microtasks).
  18. // However, it has subtle problems when state is changed right before repaint
  19. // (e.g. #6813, out-in transitions).
  20. // Also, using (macro) tasks in event handler would cause some weird behaviors
  21. // that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).
  22. // So we now use microtasks everywhere, again.
  23. // A major drawback of this tradeoff is that there are some scenarios
  24. // where microtasks have too high a priority and fire in between supposedly
  25. // sequential events (e.g. #4521, #6690, which have workarounds)
  26. // or even between bubbling of the same event (#6566).
  27. let timerFunc
  28. // The nextTick behavior leverages the microtask queue, which can be accessed
  29. // via either native Promise.then or MutationObserver.
  30. // MutationObserver has wider support, however it is seriously bugged in
  31. // UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
  32. // completely stops working after triggering a few times... so, if native
  33. // Promise is available, we will use it:
  34. /* istanbul ignore next, $flow-disable-line */
  35. // 根据判断结果给timerFunc不同的函数内容
  36. if (typeof Promise !== 'undefined' && isNative(Promise)) {
  37. const p = Promise.resolve()
  38. timerFunc = () => {
  39. p.then(flushCallbacks)
  40. // In problematic UIWebViews, Promise.then doesn't completely break, but
  41. // it can get stuck in a weird state where callbacks are pushed into the
  42. // microtask queue but the queue isn't being flushed, until the browser
  43. // needs to do some other work, e.g. handle a timer. Therefore we can
  44. // "force" the microtask queue to be flushed by adding an empty timer.
  45. if (isIOS) setTimeout(noop)
  46. }
  47. isUsingMicroTask = true
  48. } else if (!isIE && typeof MutationObserver !== 'undefined' && (
  49. isNative(MutationObserver) ||
  50. // PhantomJS and iOS 7.x
  51. MutationObserver.toString() === '[object MutationObserverConstructor]'
  52. )) {
  53. // Use MutationObserver where native Promise is not available,
  54. // e.g. PhantomJS, iOS7, Android 4.4
  55. // (#6466 MutationObserver is unreliable in IE11)
  56. let counter = 1
  57. const observer = new MutationObserver(flushCallbacks)
  58. const textNode = document.createTextNode(String(counter))
  59. observer.observe(textNode, {
  60. characterData: true
  61. })
  62. timerFunc = () => {
  63. counter = (counter + 1) % 2
  64. textNode.data = String(counter)
  65. }
  66. isUsingMicroTask = true
  67. } else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
  68. // Fallback to setImmediate.
  69. // Technically it leverages the (macro) task queue,
  70. // but it is still a better choice than setTimeout.
  71. timerFunc = () => {
  72. setImmediate(flushCallbacks)
  73. }
  74. } else {
  75. // Fallback to setTimeout.
  76. timerFunc = () => {
  77. setTimeout(flushCallbacks, 0)
  78. }
  79. }
  80. export function nextTick (cb?: Function, ctx?: Object) {
  81. let _resolve
  82. // 把传入的回调函数cb压入callbacks数组
  83. callbacks.push(() => {
  84. if (cb) {
  85. try {
  86. cb.call(ctx)
  87. } catch (e) {
  88. handleError(e, ctx, 'nextTick')
  89. }
  90. } else if (_resolve) {
  91. _resolve(ctx)
  92. }
  93. })
  94. if (!pending) {
  95. pending = true
  96. timerFunc()
  97. }
  98. // $flow-disable-line
  99. // 当nextTick不传cb参数时提供一个Promise化的调用 nextTick().then(() => {})
  100. if (!cb && typeof Promise !== 'undefined') {
  101. return new Promise(resolve => {
  102. // 当_resolve函数执行就会跳到then的逻辑中
  103. _resolve = resolve
  104. })
  105. }
  106. }

Vue.js 提供了 2 种调用 nextTick 的方式,一种是全局 API Vue.nextTick,一种是实例上的方法 vm.$nextTick,无论我们使用哪一种,最后都是调用 next-tick.js 中实现的 nextTick 方法