nextTick
// Flags whether microtasks are enabled
export let isUsingMicroTask = false
// A method to store nextTick
const callback = []
let pending = false
// Execute the nextTick method while clearing the nextTick task queue
function flushCallbacks(){
pending = false
const copies = callback.slice(0)
callback.length = 0
for(let i = 0; i < copies.length; i ++){ copies[i]() } }let timeFunc
if(typeof Promise! = ='undefined' && isNative(Promise)) {// Check whether the window environment /Node environment and Promise exist
const p = Promise.resolve()
// Perform the microtask calling nextTick based on the Promise
timeFunc = () = > {
p.then(flushCallbacks)
if(isIOS) setTimeout(noop)
}
// flag to enable microtasks
isUseingMicroTask = true
}else if(! isIE &&typeofMutationObserver ! = ='undefined' && (isNative(MutationObserver) || MutationObserver.toString() === '[object MutationObserverConstructor]')) {// Flag whether MutationObserver exists in the current non-IE environment
let counter = 1
const observer = new MutationObserver(flushCallbacks)
const textNode = document.createTextNode(String(counter))
// Monitor textNode to call nextTick
observer.observe(textNode,{
characterData: true
})
/ / textNode changes
timeFunc = () = > {
counter = (counter + 1) %2
textNode.data = String(counter)
}
// flag to enable microtasks
isUseringMicroTask = true
}else if(typeofsetImmediate ! = ='undefined' && isNative(setImmediate)){
// To determine the current Node environment,setImmediate exists
// Macro task calls nextTick
timeFunc = () = > {
setImmediate(flushCallbacks)
}
}else {
// Macro task calls nextTick
timeFunc = () = > {
setTimeout(flushCallbacks,0)}}/ / nextTick run
export function nextTick(cb,ctx){
let _resolve
// Stores tasks to nextTick's task queue
callbacks.push(() = > {
if(cb){
try{
cb.call(ctx)
}catch(e){
handleError(e,ctx,'nextTick')}}else if(_resolve){
_resolve(ctx)
}
})
// Check whether nextTick is currently executing, otherwise execute
if(! pending){ pending =true
timeFunc()
}
// Determine that no task currently exists and return the calling object
if(! cb &&typeof Promise! = ='undefined') {return new Promise(resolve= > {
_resolve = resolve
})
}
}
Copy the code