The Asynchronous Update Queue and nextTick
🎯 Introduction
Have you ever changed data ten times in a row but seen only one page update? Or read the DOM immediately after changing data and found the old content?
By the end of this article, you will understand why Vue 2 updates the DOM asynchronously, how its watcher queue deduplicates and schedules work, and how to use this.$nextTick to access the updated DOM after changing data.
🧱 Why Not Render Synchronously After Every Change?
Consider this example:
<template>
<div>{{ count }}</div>
</template>
<script>
export default {
data() {
return { count: 0 };
},
mounted() {
for (let i = 0; i < 10; i++) {
this.count++;
}
},
};
</script>
The loop changes count ten times. Rendering immediately after every change would generate virtual DOM, diff it, and patch the DOM ten times. Users would never see the first nine results, so that work would be wasted.
Vue queues the Watchers that need updating, then flushes the queue after the current synchronous work finishes. Ten changes can therefore produce a single DOM update, substantially reducing the work required.
Think of parcel delivery: sending a courier for every parcel is wasteful. Collecting a batch and delivering it together is more efficient.
⚙️ queueWatcher: Enqueue and Deduplicate
Data changes invoke a Watcher's update() method. Synchronous Watchers run directly, while lazy computed Watchers are marked dirty. Render Watchers use queueWatcher to enter the asynchronous queue.
Simplified from src/core/observer/scheduler.js:
const queue = [];
const has = {}; // IDs of Watchers already queued
let waiting = false;
function queueWatcher(watcher) {
const id = watcher.id;
// Deduplicate by ID: enqueue each Watcher once per pending flush
if (has[id] == null) {
has[id] = true;
queue.push(watcher);
// Schedule only one flush for the pending batch
if (!waiting) {
waiting = true;
nextTick(flushSchedulerQueue);
}
}
}
There are three key design choices:
- Deduplication with
has: ten changes tocountnotify the same render Watcher.has[id]ensures it enters the queue once, explaining why ten changes cause one update. - The
waitingflag: schedulesnextTick(flushSchedulerQueue)only once for the pending batch, avoiding duplicate flush tasks. - Deferred execution with
nextTick: postpones the flush until synchronous code finishes, allowing the current batch of changes to accumulate.
🛠 flushSchedulerQueue: Flush the Batch
When the scheduled callback runs, flushSchedulerQueue processes the queue. Simplified from src/core/observer/scheduler.js:
function flushSchedulerQueue() {
// Sort by ascending ID
queue.sort((a, b) => a.id - b.id);
for (let i = 0; i < queue.length; i++) {
const watcher = queue[i];
has[watcher.id] = null;
watcher.run(); // Re-render and patch the DOM
}
// Reset state for the next batch
queue.length = 0;
waiting = false;
}
Two details matter:
- Why sort? Watcher IDs increase as Watchers are created. Parent render Watchers are created before child render Watchers, so sorting ensures parents update before children, avoiding redundant child updates.
watcher.run(): performs the actual rendering throughvm._update(vm._render()), using the virtual DOM diffing process covered in the Snabbdom course.
After running the Watchers, Vue also invokes the components' updated lifecycle hooks. The DOM for each completed component update is therefore available in its updated hook.
⚡ How nextTick Works: Prefer Microtasks
The final piece is how nextTick defers execution. Simplified from src/core/util/next-tick.js:
const callbacks = [];
let pending = false;
let timerFunc;
function nextTick(cb) {
callbacks.push(cb);
if (!pending) {
pending = true;
timerFunc();
}
}
function flushCallbacks() {
pending = false;
const cbs = callbacks.slice(0);
callbacks.length = 0;
for (let i = 0; i < cbs.length; i++) {
cbs[i]();
}
}
The structure is straightforward: callbacks collects callbacks, pending ensures only one flush is scheduled for the batch, and flushCallbacks executes them when the scheduled task runs.
Vue selects timerFunc through a fallback chain, based on environment support:
// 1. Prefer Promise (microtask)
if (typeof Promise !== 'undefined') {
const p = Promise.resolve();
timerFunc = () => {
p.then(flushCallbacks);
};
}
// 2. Fall back to MutationObserver (microtask)
else if (typeof MutationObserver !== 'undefined') {
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);
};
}
// 3. Fall back to setImmediate (macrotask, available in IE and Node)
else if (typeof setImmediate !== 'undefined') {
timerFunc = () => {
setImmediate(flushCallbacks);
};
}
// 4. Finally, use setTimeout (macrotask)
else {
timerFunc = () => {
setTimeout(flushCallbacks, 0);
};
}
Why prefer microtasks? They run after the current call stack finishes and before the browser's next rendering opportunity. A macrotask runs in a later task, potentially allowing a render in between. Using a microtask applies DOM changes sooner and reduces the chance of displaying intermediate states. Modern browsers use the Promise.then branch.
💡 A Typical Use for this.$nextTick
this.$nextTick(cb) adds cb to the same callbacks array. When called after a data change, it runs after the queued update. A typical use is reading the updated DOM after changing data.
<template>
<div>
<ul ref="list">
<li v-for="item in list" :key="item">{{ item }}</li>
</ul>
<button @click="addItem">Add an item</button>
</div>
</template>
<script>
export default {
data() {
return { list: ['Apple', 'Banana'] };
},
methods: {
addItem() {
this.list.push('Orange');
// Synchronous read: the list still has its previous height
console.log('Synchronous read:', this.$refs.list.offsetHeight);
this.$nextTick(() => {
// Deferred read: the DOM has updated, so this is the new height
console.log('nextTick read:', this.$refs.list.offsetHeight);
});
},
},
};
</script>
Use Node.js v22 locally and install vue@2.7.16:
npm install vue@2.7.16
$nextTick does not execute code immediately; it waits until the pending DOM update is complete. It provides no particular benefit when you only want a delay unrelated to DOM updates.v-if / v-show for visibility and :class / :style for styling. Reserve $nextTick for work that needs the actual updated DOM, such as measuring elements or integrating a third-party DOM library.❓ Knowledge Check
Q1: Does nextTick use a microtask or a macrotask?
It depends on the environment. Modern browsers use Promise microtasks. Older environments fall back to MutationObserver (microtask), setImmediate, or setTimeout (macrotasks). Vue prefers microtasks so callbacks run promptly before the next browser render.
Q2: Why do ten data changes produce one DOM update?
All ten notify the same render Watcher. The has object in queueWatcher deduplicates by watcher.id, so that Watcher enters the queue once and renders once during the flush.
Q3: Why does reading the DOM immediately after a synchronous data change return old content?
Rendering is asynchronous. Changing data queues the Watcher; the DOM update happens when the scheduled flushSchedulerQueue runs. During the synchronous code, the DOM still contains the previous content.
Q4: Why does flushSchedulerQueue sort the queue?
It sorts by ascending Watcher ID, which reflects creation order. Parent render Watchers are created first, so parents update before children, avoiding a redundant child refresh after the parent's update affects it.
Q5: What alternatives are there to direct DOM manipulation?
Most cases can use bindings: v-if / v-show for visibility, :class / :style for styles, and interpolation or v-text for text. Use $nextTick for tasks such as measuring elements or initializing third-party chart and map libraries that require the updated DOM.
🧪 Exercise
Build a counter component whose button increments count three times in succession. Log the DOM text synchronously and in a $nextTick callback, then explain the difference.
<template>
<div>
<p ref="text">{{ count }}</p>
<button @click="addThree">Increment three times</button>
</div>
</template>
<script>
export default {
data() {
return { count: 0 };
},
methods: {
addThree() {
this.count++;
this.count++;
this.count++;
// Write your code here: log this.$refs.text.textContent synchronously
// Write your code here: log this.$refs.text.textContent in a $nextTick callback
},
},
};
</script>
🎉 You now understand Vue 2's asynchronous update queue and nextTick! Deduplicating queued Watchers and flushing them in a microtask explains how Vue batches updates.
