You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The process.nextTick() method adds the callback to the "next tick queue". Once the current turn of the event loop turn runs to completion, all callbacks currently in the next tick queue will be called.
This is not a simple alias to setTimeout(fn, 0). It is much more efficient. It runs before any additional I/O events (including timers) fire in subsequent ticks of the event loop.
Vue的API命名nextTick
Vue官方对nextTick这个API的描述:
在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。
// 修改数据vm.msg='Hello'// DOM 还没有更新Vue.nextTick(function(){// DOM 更新了})// 作为一个 Promise 使用 (2.1.0 起新增,详见接下来的提示)Vue.nextTick().then(function(){// DOM 更新了})
/* @flow *//* globals MessageChannel */import{noop}from'shared/util'import{handleError}from'./error'import{isIOS,isNative}from'./env'constcallbacks=[]letpending=falsefunctionflushCallbacks(){pending=falseconstcopies=callbacks.slice(0)callbacks.length=0for(leti=0;i<copies.length;i++){copies[i]()}}// 在2.4中使用了microtasks ,但是还是存在问题,// 在2.5版本中组合使用macrotasks和microtasks,组合使用的方式是对外暴露withMacroTask函数// 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).// 2.5版本在nextTick中对于调用microtask(微任务)还是macrotask(宏任务)声明了两个不同的变量letmicroTimerFuncletmacroTimerFunc// 默认使用microtask(微任务)letuseMacroTask=false// 这里主要定义macrotask(宏任务)函数// macrotask(宏任务)的执行优先级// setImmediate -> MessageChannel -> setTimeout// setImmediate是最理想的选择// 最Low的状况是降级执行setTimeout// 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 */if(typeofsetImmediate!=='undefined'&&isNative(setImmediate)){macroTimerFunc=()=>{setImmediate(flushCallbacks)}}elseif(typeofMessageChannel!=='undefined'&&(isNative(MessageChannel)||// PhantomJSMessageChannel.toString()==='[object MessageChannelConstructor]')){constchannel=newMessageChannel()constport=channel.port2channel.port1.onmessage=flushCallbacksmacroTimerFunc=()=>{port.postMessage(1)}}else{/* istanbul ignore next */macroTimerFunc=()=>{setTimeout(flushCallbacks,0)}}// 这里主要定义microtask(微任务)函数// microtask(微任务)的执行优先级// Promise -> macroTimerFunc// 如果原生不支持Promise,那么执行macrotask(宏任务)函数// Determine microtask defer implementation./* istanbul ignore next, $flow-disable-line */if(typeofPromise!=='undefined'&&isNative(Promise)){constp=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)}}else{// fallback to macromicroTimerFunc=macroTimerFunc}// 对外暴露withMacroTask 函数// 触发变化执行nextTick时强制执行macrotask(宏任务)函数/** * Wrap a function so that if any code inside triggers state change, * the changes are queued using a (macro) task instead of a microtask. */exportfunctionwithMacroTask(fn: Function): Function{returnfn._withTask||(fn._withTask=function(){useMacroTask=truetry{returnfn.apply(null,arguments)}finally{useMacroTask=false}})}// 这里需要注意pendingexportfunctionnextTick(cb?: Function,ctx?: Object){let_resolvecallbacks.push(()=>{if(cb){try{cb.call(ctx)}catch(e){handleError(e,ctx,'nextTick')}}elseif(_resolve){_resolve(ctx)}})if(!pending){pending=trueif(useMacroTask){macroTimerFunc()}else{microTimerFunc()}}// $flow-disable-lineif(!cb&&typeofPromise!=='undefined'){returnnewPromise(resolve=>{_resolve=resolve})}}
2.6版本
/* @flow *//* globals MutationObserver */import{noop}from'shared/util'import{handleError}from'./error'import{isIE,isIOS,isNative}from'./env'exportletisUsingMicroTask=falseconstcallbacks=[]letpending=falsefunctionflushCallbacks(){pending=falseconstcopies=callbacks.slice(0)callbacks.length=0for(leti=0;i<copies.length;i++){copies[i]()}}// 在2.5版本中组合使用microtasks 和macrotasks,但是重绘的时候还是存在一些小问题,而且使用macrotasks在任务队列中会有几个特别奇怪的行为没办法避免,So又回到了之前的状态,在任何地方优先使用microtasks 。// 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).lettimerFunc// 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 */// task的执行优先级// Promise -> MutationObserver -> setImmediate -> setTimeoutif(typeofPromise!=='undefined'&&isNative(Promise)){constp=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}elseif(!isIE&&typeofMutationObserver!=='undefined'&&(isNative(MutationObserver)||// PhantomJS and iOS 7.xMutationObserver.toString()==='[object MutationObserverConstructor]')){// Use MutationObserver where native Promise is not available,// e.g. PhantomJS, iOS7, Android 4.4// (#6466 MutationObserver is unreliable in IE11)letcounter=1constobserver=newMutationObserver(flushCallbacks)consttextNode=document.createTextNode(String(counter))observer.observe(textNode,{characterData: true})timerFunc=()=>{counter=(counter+1)%2textNode.data=String(counter)}isUsingMicroTask=true}elseif(typeofsetImmediate!=='undefined'&&isNative(setImmediate)){// Fallback to setImmediate.// Techinically 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)}}exportfunctionnextTick(cb?: Function,ctx?: Object){let_resolvecallbacks.push(()=>{if(cb){try{cb.call(ctx)}catch(e){handleError(e,ctx,'nextTick')}}elseif(_resolve){_resolve(ctx)}})if(!pending){pending=truetimerFunc()}// $flow-disable-lineif(!cb&&typeofPromise!=='undefined'){returnnewPromise(resolve=>{_resolve=resolve})}}
为什么是
nextTick
这里猜测一下为什么Vue有一个API叫
nextTick
。浏览器
浏览器(多进程)包含了Browser进程(浏览器的主进程)、第三方插件进程和GPU进程(浏览器渲染进程),其中GPU进程(多线程)和Web前端密切相关,包含以下线程:
这些线程中,和Vue的
nextTick
息息相关的是JS引擎线程和事件触发线程。JS引擎线程和事件触发线程
浏览器页面初次渲染完毕后,JS引擎线程结合事件触发线程的工作流程如下:
(1)同步任务在JS引擎线程(主线程)上执行,形成执行栈(Execution Context Stack)。
(2)主线程之外,事件触发线程管理着一个任务队列(Task Queue)。只要异步任务有了运行结果,就在任务队列之中放置一个事件。
(3)执行栈中的同步任务执行完毕,系统就会读取任务队列,如果有异步任务需要执行,将其加到主线程的执行栈并执行相应的异步任务。
主线程的执行流程如下图所示:
事件循环机制(Event Loop)
事件触发线程管理的任务队列是如何产生的呢?事实上这些任务就是从JS引擎线程本身产生的,主线程在运行时会产生执行栈,栈中的代码调用某些异步API时会在任务队列中添加事件,栈中的代码执行完毕后,就会读取任务队列中的事件,去执行事件对应的回调函数,如此循环往复,形成事件循环机制,如下图所示:
任务类型
JS中有两种任务类型:微任务(microtask)和宏任务(macrotask),在ES6中,microtask称为 jobs,macrotask称为 task。
宏任务: script (主代码块)、
setTimeout
、setInterval
、setImmediate
、I/O 、UI rendering微任务:
process.nextTick
(Nodejs) 、promise
、Object.observe
、MutationObserver
它们之间区别如下:
setTimeout
(下一个宏任务)会更快,因为无需等待UI渲染。自我灌输一下自己的理解:
根据事件循环机制,重新梳理一下流程:
举个栗子,以下示例无法直观的表述UI渲染线程的接管过程,只是表述了JS引擎线程的执行流程:
点击
inner
元素打印的顺序是:建议放入浏览器验证。触发的
click
事件会加入宏任务队列,MutationObserver
和Promise
的回调会加入微任务队列,setTimeout
加入到宏任务队列,对应的任务用对象直观的表述一下(自我认知的一种表述,只有参考价值):稍微增加一下代码的复杂度,在原有的基础上给
outer
元素新增一个click
监听事件:点击
inner
元素打印的顺序是:建议放入浏览器验证。由于冒泡,
click
函数再一次执行了,对应的任务用对象直观的表述一下(自我认知的一种表述,只有参考价值):Node.js中的
process.nextTick
Node.js中有一个
nextTick
函数和Vue中的nextTick
命名一致,很容易让人联想到一起(Node.js的Event Loop和浏览器的Event Loop有差异)。重点讲解一下Node.js中的nextTick
的执行机制,简单的举个栗子:在Node环境(10.3.0版本)中打印的顺序:
Promise 1
>Promise 2
>nextTick 1
>nextTick 2
>Promise Resolve
>timeout
在Node.js的v10.x版本中对于
process.nextTick
的说明如下:The process.nextTick() method adds the callback to the "next tick queue". Once the current turn of the event loop turn runs to completion, all callbacks currently in the next tick queue will be called.
This is not a simple alias to setTimeout(fn, 0). It is much more efficient. It runs before any additional I/O events (including timers) fire in subsequent ticks of the event loop.
Vue的API命名
nextTick
Vue官方对
nextTick
这个API的描述:Vue对于这个API的感情是曲折的,在2.4版本、2.5版本和2.6版本中对于
nextTick
进行反复变动,原因是浏览器对于微任务的不兼容性影响、微任务和宏任务各自优缺点的权衡。看以上流程图,如果Vue使用
setTimeout
等宏任务函数,那么势必要等待UI渲染完成后的下一个宏任务执行,而如果Vue使用微任务函数,无需等待UI渲染完成才进行nextTick
的回调函数操作,可以想象在JS引擎线程和GUI渲染线程之间来回切换,以及等待GUI渲染线程的过程中,浏览器势必要消耗性能,这是一个严谨的框架完全需要考虑的事情。当然这里所说的只是
nextTick
执行用户回调之后的性能情况考虑,这中间当然不能忽略flushBatcherQueue
更新Dom的操作,使用异步函数的另外一个作用当然是要确保同步代码执行完毕Dom更新之后我们可以拿到Dom的数据。到了这里,对于Vue中
nextTick
函数的命名应该是了然于心了,当然这个命名不知道和Node.js的process.nextTick
还有没有什么必然联系。Vue中NextTick源码(这里加了一些简单的注释说明)
2.5版本
2.6版本
总结
本文的表述可能存在一些不严谨的地方。
参考文献
The text was updated successfully, but these errors were encountered: