在介绍事件循环以前咱们先简单了解(回顾)一下浏览器相关常识javascript
简单理解区别就是:异步是须要延迟执行的代码css
进程:进程是应用程序的执行实例,每个进程都是由私有的虚拟地址空间、代码、数据和其它系统资源所组成;进程在运行过程当中可以申请建立和使用系统资源(如独立的内存区域等),这些资源也会随着进程的终止而被销毁html
线程:线程则是进程内的一个独立执行单元,在不一样的线程之间是能够共享进程资源的,是进程内能够调度的实体。比进程更小的独立运行的基本单位。线程也被称为轻量级进程。vue
简单讲,一个进程可由多个线程构成,线程是进程的组成部分。html5
js是单线程的,但浏览器并非,它是通常是多进程的。java
以chrome为例: 一个页签就是一个独立的进程。而javascript的执行是其中的一个线程,里面还包含了不少其余线程,如:ios
ok,常识性内容回顾完毕,咱们开始切入正题。chrome
常见的macroTask有:setTimeout、setInterval、setImmediate、i/o操做、ui渲染、MessageChannel、postMessage数组
常见的microTask有:process.nextTick、Promise、Object.observe(已废弃)、MutationObserver(html5新特性)promise
用线程的理论理解队列:
以上就是一次完整的事件循环。
整个流程用一个简单的图表示以下:
而后将macroTask中优先级最高的任务推入主线程,继续执行上述过程
注意:单次事件循环中,macroTask的任务仅处理优先级最高的那一个,而microTask要执行完全部。
通过上面的学习咱们把异步拿到的数据放在macroTask中仍是microTask中呢?
好比先放在macroTask中:
setTimeout(task, 0)
复制代码
那么按照Event loop,task会被推入macroTask中,本次调用栈内容执行完,会执行microTask中的内容,而后进行render。而本次事件循环render内容是不包含task的,由于他还在macroTask中还没有执行,须要等到下次事件循环才能进行渲染
若是放在microTask中:
Promise.resolve().then(task)
复制代码
那么按照Event loop,task会被推入microTask中,本次调用栈内容执行完,会执行microTask中的task内容,而后进行render,也就是在本次的事件循环中就能够进行渲染。
总结:咱们在异步任务中修改dom是尽可能在microTask完成。
咱们先来看一段代码
getData().then(res => {
this.xxx = res.data.xxx
this.$nextTick(() => {
// 这里咱们能够获取更新后的 DOM
})
})
复制代码
这段代码很简单,但实际上用到了两次nextTick。
this.$nextTick()是一次显式调用,没啥说的。主要是这行
this.xxx = res.data.xxx
复制代码
这一行是常见的vue参数设置,而后更新dom,那么它怎么就和nextTick产生联系了呢?
这就会涉及vue的数据响应原理
当设置新的参数时,会触发对应属性的set拦截,而后触发dep的notify方法,进而调用watcher的update方法,再由update调用queueWathcer,最终调用nextTick方法
先看个例子
data () {
return {
count: 0
}
},
mounted () {
for (let i = 0; i < 1000; i++) {
this.count++
}
}
复制代码
若是不用异步队列,每一次set劫持都作render的话,那么render会执行1000次,会很是浪费性能。
若是把这些更新统统放在异步队列里,意味着,会触发1000次watcher的queueWathcer方法。 但有一点注意,queueWathcer里面经过id对watcher作了去重处理,虽然被调用了1000次,但有效调用只有一次。同时也保证,在一个ticket中,同一个参数即便被修改屡次,咱们在执行wather.update时候仍然保证渲染的是最新的数据。
因此使用nextTick进行渲染,也是vue的一大优化
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的实现。 核心逻辑:
因此vue的数据更新是一个异步的过程。
仍是以前的例子
getData().then(res => {
this.xxx = res.data.xxx
this.$nextTick(() => {
// 这里咱们能够获取更新后的 DOM
})
})
复制代码
这里提一个疑问~
前面不是说UI Render是在microTask都执行完以后才进行么。
而经过对vue的$nextTick分析,它实际是用promise包装的,属于microTask。
在getData.then中,执行了this.xxx= res.data,它实际也是经过wather调用$nextTick
随后,又执行了一个$nextTick
按理说目前还处在同一个事件循环,并且尚未进行UI Render,怎么在$nextTick就能拿到刚渲染的dom呢?
咱们先看一个例子
<template>
<div>
<div class="title" ref="test">{{title}}</div>
</div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
@Component
export default class Index extends Vue {
// 和vue data()是同样的,咱们这里是ts写法
title: string = 'nothing'
mounted () {
// 模拟接口获取数据
setTimeout(() => {
this.title = '测试标题'
this.$nextTick(() => {
console.log('debug:', this.title, this.$refs.test['innerHTML'])
alert('渲染完了么?')
})
}, 0)
}
</script>
<style lang="scss">
.title{
font-size: pxToRem(158px);
text-align: center;
}
</style>
复制代码
看看浏览器的渲染状况
由于alert可以阻塞渲染,因此这里用到它。
在alert以前咱们console了最新设置dom的内容,从控制台已经拿到了最新设置的title。可是浏览器尚未进行渲染。再点击“肯定”后,浏览器才进行渲染。
我以前一直觉得获取新的dom节点必须等UI Render完成以后才能获取到,然而并非这样的。
结论:
在主线程及microTask执行过程当中,每一次dom或css更新,浏览器都会进行计算,而计算的结果并不会被马上渲染,而是在当全部的microTask队列中任务都执行完毕后,统一进行渲染(这也是浏览器为了提升渲染性能和体验作的优化)因此,这个时候经过js访问更新后的dom节点或者css是能够拿到的,由于浏览器已经完成计算,仅仅是它们还没被渲染而已。
这也就完美解决了我以前的疑问。
OK,以上就是对浏览器事件循环所有介绍,欢迎你们学习交流