nextTick的原理
实现:
let callbacks = []; // 回调函数
let pending = false;
function flushCallbacks(){
pending = false; // 把标志还原为false
for (let i = 0; i < callbacks.length; i++) {
callbacks[i]();
}
}
let timerFunc;// 先采用微任务并按照优先级优雅降级的方式实现异步刷新
if (typeof Promise !== "undefined") {
// 如果支持 promise
const p = Promise.resolve();
timerFunc = () => {
p.then(flushCallbacks);
}
} else if (typeof MutationObserver !== "undefined") {
// MutatuonObserver 主要是监听dom变化,也是一个异步方法
let counter = 1;
const ovserver = new MutationObserver(flushCalbacks);
const textNode = document.createTextNode(String(counter));
observer.observe(textNode, {
characterData: true,
});
timerFunc = () => {
counter = (counter + 1) % 2;
textNode.data = String(counter);
};
} else if(typeof setImmediate !== "undefined") {
// 如果前面都不支持 判断setImmediate
timerFunc = () => {
setImmediate(flushCallbacks);
};
} else {
// 最后降级采用setTimeout
timerFunc = () => {
setTimeout(flushCallbacks,0);
}
}
export function nextTick(cb) {
callbacks.push(cb);
if (!pending) {
pending = true;
timerFunc();
}
}