• The callback in nextTick is inNext DOM update loopLater executedThe callback. Use this method immediately after modifying the data to get the updated DOM.
  • The main idea of implementation is: adoptMicrotask-first approachCall asynchronous methods to execute the methods in nextTick.

Depending on compatibility, nextTick takes advantage of different methods based on whether or not they are available in the browser.

In general, the priority is: promise.then===>MutationObserver===>setTimeout

Related codes:

let callbacks = [];
let pending = false;
function flushCallbacks() {
  pending = false; // Return the flag to false
  // Execute the callbacks in turn
  for (let i = 0; i < callbacks.length; i++) { callbacks[i](); }}let timerFunc; // Define asynchronous methods using graceful degradation
if (typeof Promise! = ="undefined") {
  // If promise is supported
  const p = Promise.resolve();
  timerFunc = () = > {
    p.then(flushCallbacks);
  };
} else if (typeofMutationObserver ! = ="undefined") {
  // MutationObserver mainly listens for DOM changes and is also an asynchronous method
  let counter = 1;
  const observer = new MutationObserver(flushCallbacks);
  const textNode = document.createTextNode(String(counter));
  observer.observe(textNode, {
    characterData: true}); timerFunc =() = > {
    counter = (counter + 1) % 2;
    textNode.data = String(counter);
  };
} else if (typeofsetImmediate ! = ="undefined") {
  SetImmediate does not support mediate
  timerFunc = () = > {
    setImmediate(flushCallbacks);
  };
} else {
  // Finally demote using setTimeout
  timerFunc = () = > {
    setTimeout(flushCallbacks, 0);
  };
}

export function nextTick(cb) {
  // In addition to rendering Watcher, the user's own manual call to nextTick is collected into the array
  callbacks.push(cb);
  if(! pending) {// If nextTick is called multiple times, only one async will be executed until the async queue is cleared and the flag is set to false
    pending = true; timerFunc(); }}Copy the code