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~
// 在其他情況下 優(yōu)先使用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
// 通過監(jiān)聽這個節(jié)點的變化,保證nexitTick執(zhí)行時dom已經(jīng)變更成功
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執(zhí)行時步驟如下
【侵刪】
image
這個過程就是event loop了。深入的內(nèi)容還有運行棧恋腕,執(zhí)行上下文等抹锄,后續(xù)再深入了解。
有幾點說明一下:1荠藤,event loop 不是js語言特性伙单,而是運行環(huán)境機制。是由運行環(huán)境實現(xiàn)的哈肖,在不同的運行環(huán)境中车份,內(nèi)部實現(xiàn)可能不同(node.js,各種瀏覽器)
標準在這里:https://www.w3.org/TR/html5/webappapis.html#event-loops
2:這個圖片中沒有說明的是在一次循環(huán)結束后牡彻,瀏覽器會進行更新渲染(Update the rendering)
event loop中一個有意思的地方是每次執(zhí)行完一個宏任務后將執(zhí)行微任務隊列中所有(劃重點)任務
所以會出現(xiàn)下面的輸出結果
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
然后我就想到一個問題扫沼,當正在執(zhí)行微任務隊列中的任務時,添加新的微任務庄吼。會立刻增加到當前微任務隊列中嗎缎除?于是有了下面的嘗試
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');