欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

浏览器事件循环与vue nextTicket的实现

程序员文章站 2022-08-18 16:36:40
同步:就是在执行栈中(主线程)执行的代码 异步:就是在异步队列(macrotask、microtask)中的代码 简单理解区别就是:异步是需要延...
  • 同步:就是在执行栈中(主线程)执行的代码
  • 异步:就是在异步队列(macrotask、microtask)中的代码

简单理解区别就是:异步是需要延迟执行的代码

线程和进程

  • 进程:进程是应用程序的执行实例,每一个进程都是由私有的虚拟地址空间、代码、数据和其它系统资源所组成;进程在运行过程中能够申请创建和使用系统资源(如独立的内存区域等),这些资源也会随着进程的终止而被销毁
  • 线程:线程则是进程内的一个独立执行单元,在不同的线程之间是可以共享进程资源的,是进程内可以调度的实体。比进程更小的独立运行的基本单位。线程也被称为轻量级进程。

简单讲,一个进程可由多个线程构成,线程是进程的组成部分。

js是单线程的,但浏览器并不是,它是一般是多进程的。

以chrome为例: 一个页签就是一个独立的进程。而javascript的执行是其中的一个线程,里面还包含了很多其他线程,如:

  • gui渲染线程
  • http请求线程
  • 定时器触发线程
  • 事件触发线程
  • 图片等资源的加载线程。

事件循环

ok,常识性内容回顾完,我们开始切入正题。

microtask 和 macrotask

常见的macrotask有:settimeout、setinterval、setimmediate、i/o操作、ui渲染、messagechannel、postmessage

常见的microtask有:process.nexttick、promise、object.observe(已废弃)、mutationobserver(html5新特性)

用线程的理论理解队列:

macrotask由事件触发线程维护
microtask通常由js引擎自己维护

一个完整的事件循环(event loop)过程解析

  • 初始状态:调用栈(主线程)、microtask队列、macrotask队列,macrotask里只有一个待执行的script脚本(如:入口文件)
  • 将这个script推入调用栈,同步执行代码。在这过程中,会调用一些接口或者触发一些事件,可产生新的marcotask与microtask。它们分别会被推入各自的任务队列。同时该script脚本会被从macrotask中移除,在调用栈执行的过程就称之为一个tick。
  • 调用栈代码执行完成后,需要处理的是microtask中的任务。将里面的任务依次推入调用栈执行。
  • 待microtask 所有 的任务都执行完成后,再去macrotask中获取优先级最高的任务推入调用栈。
  • 执行渲染操作,更新界面
  • 查看是否有web worker,如果有,则对其进行处理。

(上述过程循环往复,直到两个队列都清空)

浏览器事件循环与vue nextTicket的实现

注意:处理microtask中的任务时,是执行完所有的任务。而处理macrotask的任务时是一个一个执行。

渲染时机

经过上面的学习我们把异步拿到的数据放在macrotask中还是microtask中呢?

比如先放在macrotask中:

settimeout(mytask, 0)

那么按照event loop,mytask会被推入macrotask中,本次调用栈内容执行完,会执行microtask中的内容,然后进行render。而此次render是不包含mytask中的内容的。需要等到 下一次事件循环 (将mytask推入执行栈后)才能执行。

如果放在microtask中:

promise.resolve().then(mytask)

那么按照event loop,mytask会被推入microtask中,本次调用栈内容执行完,会执行microtask中的mytask内容,然后进行render,也就是在 本次的事件循环 中就可以进行渲染。

总结:我们在异步任务中修改dom是尽量在microtask完成。

vue next-tick实现

vue2.5以后,采用单独的next-tick.js来维护它。

import { noop } from 'shared/util'
import { handleerror } from './error'
import { isios, isnative } from './env'

// 所有的callback缓存在数组中
const callbacks = []
// 状态
let pending = false

// 调用数组中所有的callback,并清空数组
function flushcallbacks () {
 // 重置标志位
 pending = false
 const copies = callbacks.slice(0)
 callbacks.length = 0
 // 调用每一个callback
 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).

// 微任务function
let microtimerfunc
// 宏任务fuction
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 */

// 优先检查是否支持setimmediate,这是一个高版本 ie 和 edge 才支持的特性(和settimeout差不多,但优先级最高)
if (typeof setimmediate !== 'undefined' && isnative(setimmediate)) {
 macrotimerfunc = () => {
  setimmediate(flushcallbacks)
 }
// 检查messagechannel兼容性(优先级次高)
} 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 */

// 微任务用promise来处理
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)
 }
// promise不支持直接用宏任务
} 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.
 */
// 强制走宏任务,比如dom交互事件,v-on (这种情况就需要强制走macrotask)
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
 // 缓存传入的callback
 callbacks.push(() => {
  if (cb) {
   try {
    cb.call(ctx)
   } catch (e) {
    handleerror(e, ctx, 'nexttick')
   }
  } else if (_resolve) {
   _resolve(ctx)
  }
 })
 // 如果pending为false,则开始执行
 if (!pending) {
  // 变更标志位
  pending = true
  if (usemacrotask) {
   macrotimerfunc()
  } else {
   microtimerfunc()
  }
 }
 // $flow-disable-line
 // 当为传入callback,提供一个promise化的调用
 if (!cb && typeof promise !== 'undefined') {
  return new promise(resolve => {
   _resolve = resolve
  })
 }
}

这段代码主要定义了vue.nexttick的实现。 核心逻辑:

  • 定义当前环境支持的microtimerfunc和macrotimerfunc(调用时会执行flushcallbacks方法)
  • 调用nexttick时,缓存传入的callback
  • pending设置为false,执行microtimerfunc或macrotimerfunc(也就是执行flushcallbacks方法)
  • pending设置为true,执行完数组中的callbakc,清空数组

vue在this.xxx=xxx进行节点更新时,实际上是触发了watcher的queuewatcher

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
   nexttick(flushschedulerqueue)
  }
 }
}

queuewatcher做了在一个tick内的多个更新收集。

具体逻辑我们在这就不专门讨论了(有兴趣的可以去查阅vue的观察者模式),逻辑上就是调用了nexttick方法

所以vue的数据更新是一个异步的过程。

那么我们在vue逻辑中,当想获取刚刚渲染的dom节点时我们应该这么写

你肯定会说应该这么写

getdata(res).then(()=>{
 this.xxx = res.data
 this.$nexttick(() => {
  // 这里我们可以获取变化后的 dom
 })
})

没错,确实应该这么写。

那么问题来了~

前面不是说ui render是在microtask都执行完之后才进行么。

而通过对vue的$nexttick分析,它实际是用promise包装的,属于microtask。

在getdata.then中,执行了this.xxx= res.data,它实际也是通过wather调用$nexttick

随后,又执行了一个$nexttick

按理说目前还处在同一个事件循环,而且还没有进行ui render,怎么在$nexttick就能拿到刚渲染的dom呢?

我之前被这个问题困扰了很久,最终通过写test用例发现,原来ui render这块我理解错了

ui render理解

之前一直以为新的dom节点必须等ui render之后渲染才能获取到,然而并不是这样的。

在主线程及microtask执行过程中,每一次dom或css更新,浏览器都会进行计算,而计算的结果并不会被立刻渲染,而是在当所有的microtask队列中任务都执行完毕后,统一进行渲染(这也是浏览器为了提高渲染性能和体验做的优化)所以,这个时候通过js访问更新后的dom节点或者css是可以访问到的,因为浏览器已经完成计算,仅仅是它们还没被渲染而已。

总结

以上所述是小编给大家介绍的浏览器事件循环与vue nextticket的实现,希望对大家有所帮助