The Scheduler and nextTick: Implementing Batched Updates

Learn how Vue 3 batches multiple data changes into one update through queueJob, flushJobs, and nextTick.

🎯 Introduction

If an event handler increments count.value ten times in a row, does the page render ten times? It updates once. How are the other nine renders avoided?

This article explores Vue 3's scheduler, which records pending component updates and runs them together after the current synchronous code finishes. By the end, you will be able to:

  • Explain why Vue queues updates instead of rendering immediately.
  • Describe how queueJob deduplication works with flushJobs.
  • Explain what nextTick waits for and why its callback follows pending DOM updates.
  • Write a mini scheduler that combines three consecutive changes into one update.

The excerpts use Vue 3.5.x from the GitHub vuejs/core monorepo, primarily packages/runtime-core/src/scheduler.ts. Run the standalone examples with Node.js v22.


🧱 Why Schedule Updates?

Why not render immediately whenever data changes?

As previous articles explained, changing reactive data can rerun a component's render effect. If every mutation rendered immediately, this loop would cause ten renders:

function handleClick() {
    // Increment count ten times, requesting an update each time
    for (let i = 0; i < 10; i++) {
        count.value++;
    }
}

The user would only see the final result. The preceding nine renders would do unnecessary work, which becomes costly with many components.

Vue 3 instead queues a component update job when data changes, then processes the queue after the synchronous code finishes. In this simplified model, the queue is an array processed in order.

Recording work first and executing it together is the scheduler's role.


🧱 queueJob: Adding Jobs to the Queue

How does Vue accumulate updates?

Each component render effect has an update job: a function that updates the component when called. The scheduler maintains a global queue, and queueJob adds jobs when reactive data changes. First, the shared state:

// Simplified from packages/runtime-core/src/scheduler.ts
const queue = []; // Pending update jobs
let isFlushing = false; // Whether the queue is being processed
let isFlushPending = false; // Whether a flush has already been scheduled
const resolvedPromise = Promise.resolve(); // Reused to schedule a microtask

Next, the enqueueing logic:

function queueJob(job) {
    // Deduplicate: do not enqueue the same job twice
    if (!queue.includes(job)) {
        queue.push(job); // Append the new job
        queueFlush(); // Schedule a flush
    }
}

function queueFlush() {
    // Schedule only if no flush is running or pending
    if (!isFlushing && !isFlushPending) {
        isFlushPending = true; // Mark the flush as scheduled
        // Run flushJobs in a microtask, explained below
        resolvedPromise.then(flushJobs);
    }
}

Two design choices matter:

  • Deduplication. Ten changes to the same component's state request the same job. The first enqueues it; includes rejects the next nine.
  • One scheduled flush. isFlushPending prevents each newly queued job from scheduling another flushJobs microtask.
The full scheduler also uses job metadata and component IDs to manage queued status and execution order. This teaching version compares function references with includes; the deduplication principle is the same.

🧱 flushJobs: Processing the Queue in a Microtask

When do queued jobs execute?

flushJobs runs each job and resets the scheduler for the next batch:

// Simplified from packages/runtime-core/src/scheduler.ts
function flushJobs() {
    isFlushPending = false; // The scheduled flush has started
    isFlushing = true; // Mark the queue as running

    try {
        let job;
        // Jobs added during this loop are processed in the same flush
        while ((job = queue.shift())) {
            job(); // Update the corresponding component
        }
    } finally {
        // Reset state even if a job throws
        isFlushing = false;
        queue.length = 0;
    }
}

The important timing comes from resolvedPromise.then(flushJobs). Synchronous code executes directly on the current call stack. Microtasks, including Promise callbacks, run after that synchronous execution finishes. Tasks, often called macrotasks, include timer callbacks. A useful simplified browser sequence is synchronous execution → microtasks → rendering opportunity → a later task.

Scheduling flushJobs as a microtask places it after synchronous mutations and before a subsequent browser rendering opportunity:

  • Synchronous changes are batched. All ten increments finish before flushJobs runs, so the component renders the final value once.
  • Intermediate states stay invisible. The DOM update completes before the browser paints the resulting frame.

Using setTimeout would defer the update to a later task, potentially allowing the browser to paint the old UI first.

Because DOM updates wait until synchronous execution finishes, reading the DOM immediately after changing state returns the previous content. Use nextTick when you need the updated DOM.

🧱 Implementing nextTick

How do you access the updated DOM when rendering is deferred? That is what nextTick provides.

nextTick waits for Vue's pending DOM updates before running your callback. Since flushJobs performs those updates, the callback can follow its Promise:

// Simplified from packages/runtime-core/src/scheduler.ts
let currentFlushPromise = null; // Promise for the current scheduled flush

function nextTick(fn) {
    // Follow the current flush if one exists;
    // otherwise, use an already-resolved Promise
    const p = currentFlushPromise || resolvedPromise;
    // Chain a callback, or return the Promise for awaiting
    return fn ? p.then(fn) : p;
}

There are two cases:

  • An update is pending. currentFlushPromise represents that flush, so the callback follows flushJobs.
  • No update is pending. The callback follows resolvedPromise and runs in a microtask without waiting for an unnecessary flush.

The ordering follows from the Promise chain: flushJobs comes before the nextTick callback. In the complete scheduler, queueFlush assigns its scheduled Promise to currentFlushPromise.

Verify this in a Vue 3.5.x component:

App.vue
<script setup>
import { ref, nextTick } from 'vue';

const count = ref(0);

async function handleClick() {
    count.value++;
    // Still synchronous: on the first click, the DOM contains the old value 0
    console.log('DOM immediately after mutation:', document.querySelector('#count').textContent);

    await nextTick(); // Wait for Vue's DOM update
    // After nextTick, the first click's new value is 1
    console.log('DOM after nextTick:', document.querySelector('#count').textContent);
}
</script>

<template>
    <div id="count">{{ count }}</div>
    <button @click="handleClick">+1</button>
</template>

On the first click, the first log prints 0 and the second prints 1, confirming the ordering.


⚡ Comparing nextTick with Vue 2

Vue 2's asynchronous updates and nextTick follow the same principle: queue updates and flush them asynchronously, preferably through microtasks. The implementation details differ:

  • Vue 2 supports older environments with fallbacks, preferring Promise, then alternatives such as MutationObserver, and eventually timers.
  • Vue 3 targets modern environments with Promise support and uses Promise microtasks directly.

The batching principle remains; Vue 3 removes legacy compatibility paths. You only need to recognize the fallback strategy, not memorize it.


❓ Questions and Answers

Q1: Why use microtasks rather than timer tasks for batching?

Microtasks let Vue update the DOM before a subsequent rendering opportunity, so the browser can paint the final UI. A later timer task may allow the old content to be painted first.

Q2: What does an immediate DOM read after a state change return?

The old DOM. The synchronous code is still running, so the flush microtask has not executed. Read after await nextTick() to access the updated DOM.

Q3: How do await nextTick() and nextTick(callback) differ?

Both place subsequent work after the pending flush Promise. Without a callback, nextTick returns that Promise, allowing a flatter async/await flow. Choose whichever fits your code.

Q4: Is nextTick restricted to components?

No. The function exported from vue can be called anywhere. It follows the pending flush Promise, or a resolved Promise if none exists. Options API this.$nextTick uses the same underlying mechanism.


🧪 Exercise

Complete this mini scheduler without looking up the implementation. Three consecutive changes should log just one update. Save it as a .js file and run with Node.js v22:

const queue = [];
let isFlushPending = false;

function queueJob(job) {
    // Your code here (hint: deduplicate, enqueue, and schedule one Promise-based flush)
}

function flushJobs() {
    // Your code here (hint: run all jobs, clear the queue, and reset the flag)
}

function nextTick(fn) {
    // Your code here (hint: chain fn after the Promise)
}

// ====== Verification code; no changes needed below ======
let data = { count: 0 };

function update() {
    console.log('Updating, count =', data.count);
}

// Simulate three consecutive mutations
data.count++;
queueJob(update);
data.count++;
queueJob(update);
data.count++;
queueJob(update);

nextTick(() => {
    console.log('nextTick: update complete');
});

// Expected output (one update):
// Updating, count = 3
// nextTick: update complete

For an extra challenge, call queueJob again while flushJobs is running. Can your implementation process the new job in the same flush? Consider how a while loop or a for loop handles a changing queue.


🎉 You now understand Vue 3's scheduler and nextTick! The reactive update path is complete: data changes notify effects, component jobs enter a queue, and a microtask flushes the batch. Next, we will examine virtual DOM and how patching compares old and new vnodes to update the real DOM precisely.