标签:循环 http 异步任务 undefined alt syn pos flush wrap
在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。
怎么实现的延迟回调
vue 大多数情况下优先使用微任务, 很少的地方使用宏任务
if (typeof setImmediate !== ‘undefined‘ && isNative(setImmediate)) {
macroTimerFunc = () => {
setImmediate(flushCallbacks)
}
}
setImmediate 浏览器支持情况
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)
}
}
MessageChannel 浏览器支持情况
else {
/* istanbul ignore next */
macroTimerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}
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
}
从源码中可以看出,在DOM事件中使用Vue.nextTick 默认使用宏任务, 其他地方使用Vue.nextTick默认使用微任务。
其实从源码中注释中可以看出Vue最开始都是使用微任务方式,后面出现了bug,才引入了宏任务方式
// 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).
产考资料: JavaScript 运行机制详解:再谈Event Loop
标签:循环 http 异步任务 undefined alt syn pos flush wrap
原文地址:https://www.cnblogs.com/homehtml/p/11801626.html