event Loop入门
先来一个练习题思考一下。
console.log('script start');
setTimeout(function () {
console.log('setTimeout');
}, 0);
Promise.resolve()
.then(function () {
console.log('promise1');
})
.then(function () {
console.log('promise2');
});
console.log('script end');
1.什么是event Loop
Event Loop 是一个很重要的概念,指的是计算机系统的一种运行机制。
JavaScript语言就采用这种机制,来解决单线程运行带来的一些问题。
想要理解Event Loop,就要从程序的运行模式讲起。运行以后的程序叫做"进程"(process),一般情况下,一个进程一次只能执行一个任务。
如果有很多任务需要执行,不外乎三种解决方法。
(1)排队。因为一个进程一次只能执行一个任务,只好等前面的任务执行完了,再执行后面的任务。
(2)新建进程。使用fork命令,为每个任务新建一个进程。
(3)新建线程。因为进程太耗费资源,所以如今的程序往往允许一个进程包含多个线程,由线程去完成任务。(进程和线程的详细解释,请看这里。)
以JavaScript语言为例,它是一种单线程语言,所有任务都在一个线程上完成,即采用上面的第一种方法。一旦遇到大量任务或者遇到一个耗时的任务,网页就会出现"假死",因为JavaScript停不下来,也就无法响应用户的行为。
参考说明: www.ruanyifeng.com/blog/2013/1…
总结来说: event Loop 指的是计算机执行代码的一种处理方式,下面我们来讲讲JavaScript
中的event Loop 机制
2.js event Loop 运行模型
我们主要把event Loop 分为3个部分,执行中的stack 待执行的 宏任务,排队执行的微任务。
3.常见的微任务和宏任务
这里我们暂时不讲解nodejs 中的event Loop,node虽然用的是谷歌的v8引擎但是和浏览器中的event Loop 还是有些差异。
4.任务具体是怎么调度的
console.log(1)
console.log(2)
// 1
// 2
function clg () {
console.log(2)
}
console.log(1)
clg()
// 1
// 2
console.log(1)
setTimeout(()=>{
console.log(2)
},0)
console.log(3)
// 1
// 3
// 2
console.log(1)
Promise.resolve().then(()=>{
console.log(2)
})
console.log(3)
// 1
// 3
// 2
console.log(1)
Promise.resolve().then(()=>{
console.log(2)
})
setTimeout(()=>{
console.log(3)
},0)
console.log(4)
// 1
// 4
// 2
// 3
这里已经开始有点深入了,我们把setTimeout 和 Promise 的顺序调换一下看看输出
console.log(1)
setTimeout(()=>{
console.log(3)
},0)
Promise.resolve().then(()=>{
console.log(2)
})
console.log(4)
// 1
// 4
// 2
// 3
我们会发现输出还是Promise 在前。
上面表格中有对这两种回调做出分类
setTimeout 是属于宏任务,Promise.then 是属于微任务。
我们再来一个复杂点的
console.log(1)
setTimeout(()=>{
console.log(3)
Promise.resolve(5).then(console.log)
setTimeout(()=>{
console.log('a')
Promise.resolve('b').then(console.log)
},200)
},0)
setTimeout(()=>{
console.log('timeout2')
},2000)
Promise.resolve().then(()=>{
console.log(2)
Promise.resolve('2-promise').then(console.log)
})
console.log(4)
// 1
// 4
// 2
// 2-promise
// 3
// 5
// a
// b
// timeout2
这个已经很全面了,我们下面开始解析一下为何会这样执行
js运行的过程大致是这样的
1.首先由上到下解析,遇到普通代码直接执行并输出
2.遇到宏任务,会将宏任务回调放到宏任务堆栈中等待。遇到微任务,会将微任务回调放到微任务队列中等待。
3.当前代码块执行结束后,马上会去调度,刚刚放入的微任务队列(依次全部取出执行输出)
4.微任务队列执行完毕后,从宏任务队列中取出一个最先完成的回调执行(每轮只取一个)。
5.在代码块中循环的使用上面的过程进行解析
在线图解:jakearchibald.com/2015/tasks-…
5.Event Loop 机制在vue 和 react中的使用
/* @flow */
/* globals MutationObserver */
import { noop } from 'shared/util'
import { handleError } from './error'
import { isIE, isIOS, isNative } from './env'
export let isUsingMicroTask = false
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 microtasks.
// In 2.5 we used (macro) tasks (in combination with microtasks).
// However, it has subtle problems when state is changed right before repaint
// (e.g. #6813, out-in transitions).
// Also, using (macro) tasks in event handler would cause some weird behaviors
// that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).
// So we now use microtasks everywhere, again.
// A major drawback of this tradeoff is that there are some scenarios
// where microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690, which have workarounds)
// or even between bubbling of the same event (#6566).
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)
}
}
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
})
}
}