簡單理解區別就是:異步是需要延遲執行的代碼
線程和進程
簡單講,一個進程可由多個線程構成,線程是進程的組成部分。
js是單線程的,但瀏覽器并不是,它是一般是多進程的。
以chrome為例: 一個頁簽就是一個獨立的進程。而javascript的執行是其中的一個線程,里面還包含了很多其他線程,如:
事件循環
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中還是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).// 微任務functionlet microTimerFunc// 宏任務fuctionlet 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在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的實現,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
新聞熱點
疑難解答