vue的使用中有时会用到nextTick方法,以下是nexttick中的部分源码(稍微增加了几句说明与吐槽~)
// 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:
// 上面解释了为什么在native不使用MutationObserver,居然是因为ios的一个bug~
// 在其他情况下 优先使用MutationObserver
/* istanbul ignore next, $flow-disable-line */
// 首先判定 Promise可用 并且是native端
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.
// UIWebview是ios的webview组件(旧)。特殊处理了一下
if (isIOS) setTimeout(noop)
}
isUsingMicroTask = true
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
// PhantomJS and iOS 7.x
MutationObserver.toString() === '[object MutationObserverConstructor]'
)) { // ie...... 如果MutationObserver 可用的话 使用MutationObserver
// Use MutationObserver where native Promise is not available,
// e.g. PhantomJS, iOS7, Android 4.4
// (#6466 MutationObserver is unreliable in IE11)
// 这里就是大家都在说的 隐形的text
// 通过监听这个节点的变化,保证nexitTick执行时dom已经变更成功
let counter = 1
const observer = new MutationObserver(flushCallbacks)
const textNode = document.createTextNode(String(counter))
observer.observe(textNode, {
characterData: true
})
timerFunc = () => {
counter = (counter + 1) % 2 // 0 1 0 1 0 比 += 1 好
textNode.data = String(counter)
}
isUsingMicroTask = true
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
// 然后检测是否支持setImmediate
// Fallback to setImmediate.
// Techinically it leverages the (macro) task queue,
// but it is still a better choice than setTimeout.
timerFunc = () => {
setImmediate(flushCallbacks)
}
} else {
// 最后的方案 setTimeout
// Fallback to setTimeout.
timerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}
最顶部有一句解释
// The nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
这里说到了microtask(微任务),与之对应的是macrotasks(微任务)。他们包含的api如下
macrotasks: setTimeout, setInterval, setImmediate, I/O, UI rendering,requestAnimationFrame(浏览器)
microtasks: process.nextTick(node), Promises, Object.observe(废弃), MutationObserver(浏览器)
js的任务队列与之对应,microtask queues(微任务队列)与macrotasks queues(宏任务队列)。js执行时步骤如下
【侵删】
这个过程就是event loop了。深入的内容还有运行栈,执行上下文等,后续再深入了解。
有几点说明一下:1,event loop 不是js语言特性,而是运行环境机制。是由运行环境实现的,在不同的运行环境中,内部实现可能不同(node.js,各种浏览器)
标准在这里:https://www.w3.org/TR/html5/webappapis.html#event-loops
2:这个图片中没有说明的是在一次循环结束后,浏览器会进行更新渲染(Update the rendering)
event loop中一个有意思的地方是每次执行完一个宏任务后将执行微任务队列中所有(划重点)任务
所以会出现下面的输出结果
console.log('0');
setTimeout(() => console.log('4'), 0);
Promise.resolve().then(()=> console.log('2'));
Promise.resolve().then(()=> console.log('3'));
console.log('1');
// 0
// 1
// 2
// 3
然后我就想到一个问题,当正在执行微任务队列中的任务时,添加新的微任务。会立刻增加到当前微任务队列中吗?于是有了下面的尝试
console.log('0');
setTimeout(() => {
console.log('4');
}, 0);
Promise.resolve().then(()=>{
console.log('2');
Promise.resolve().then(()=>{
console.log('3');
})
})
console.log('1');
// 0
// 1
// 2
// 3
// 4
最后,下面的输出顺序~捋一捋~
console.log('0');
setTimeout(() => {
Promise.resolve().then(()=>{
console.log('2');
Promise.resolve().then(()=>{
console.log('4');
}).then(()=>{
console.log('7');
})
}).then(()=>{
console.log('5');
})
Promise.resolve().then(()=>{
console.log('3');
}).then(()=>{
console.log('6');
})
}, 0);
setTimeout(() => {
console.log('8');
}, 0);
console.log('1');