Node.js

What Is the Difference Between Microtasks and Macrotasks?

JavaScript uses an event loop to manage asynchronous operations. Two important concepts in this process are microtasks and macrotasks. Understanding their…

D
DevByteTechnical Author
Published
14 min read3 views
What Is the Difference Between Microtasks and Macrotasks?

When working with JavaScript, you might have noticed something interesting: the order in which you write your code is not always the order in which every callback executes.

For example, a setTimeout() callback might execute after a Promise callback, even when the timer is registered first. Similarly, queueMicrotask() can execute before a timer callback, even if both functions are scheduled during the same synchronous operation.

At first, this behavior can be confusing. You might wonder why JavaScript does not simply execute every callback in the order it was written.

The answer lies in how JavaScript handles asynchronous operations through the event loop, task queues, and microtask queues.

Understanding these concepts is useful when working with Promises, async/await, timers, browser events, and Node.js applications. It can also help when debugging situations where callbacks execute in an unexpected order.

In this article, I'll explain what microtasks and macrotasks are, how they work, what makes them different, and how JavaScript decides which callback to execute first.

What Are Microtasks and Macrotasks in JavaScript?

JavaScript executes synchronous code first. When an asynchronous operation schedules a callback, that callback is placed into a queue or scheduling mechanism that determines when it can execute.

In browser JavaScript, two important categories are commonly used to explain this behavior:

  • Microtasks: High-priority jobs that are processed after the current JavaScript execution finishes and before the browser proceeds to another task.

  • Macrotasks: A commonly used informal name for regular event-loop tasks, such as timer callbacks, user interaction events, and many I/O-related tasks.

The term macrotask is widely used in tutorials and technical discussions, but the HTML standard generally calls these simply tasks.

Microtasks and tasks follow different scheduling rules, which is why their callbacks can execute in a different order from the order in which they were registered.

Let's look at a simple example.

console.log("Start");

setTimeout(() => {
  console.log("Timeout callback");
}, 0);

Promise.resolve().then(() => {
  console.log("Promise callback");
});

console.log("End");

Output in a typical browser environment:

Start
End
Promise callback
Timeout callback

Notice that the Promise callback executes before the timer callback.

Why does this happen?

First, JavaScript executes the synchronous statements and prints "Start" and "End".

Next, the Promise handler runs as a microtask. After the microtask queue has been processed, the browser can proceed to a timer task when that timer is eligible to run.

Even though setTimeout() appears before Promise.resolve().then(), its callback executes later.

This is one of the easiest ways to understand the difference between microtasks and tasks.

What Is a Microtask?

A microtask is a scheduled job that runs after the current JavaScript execution finishes, at a microtask checkpoint.

In browser JavaScript, the runtime processes the microtask queue until it is empty before moving on to another task. If a microtask schedules additional microtasks, those can run during the same checkpoint.

Microtasks are commonly used for Promise handlers and queueMicrotask() callbacks.

Examples include:

  • .then() handlers on Promises.

  • .catch() handlers on Promises.

  • .finally() handlers on Promises.

  • Callbacks scheduled using queueMicrotask().

Let's look at an example.

console.log("First");

Promise.resolve().then(() => {
  console.log("Second");
});

queueMicrotask(() => {
  console.log("Third");
});

console.log("Fourth");

Output:

First
Fourth
Second
Third

Let's break it down.

First, "First" is printed.

Next, the Promise handler and the queueMicrotask() callback are scheduled. Neither callback interrupts the synchronous execution.

JavaScript then prints "Fourth".

After the synchronous code finishes, the microtask queue is processed in the order the two microtasks were queued. The Promise handler prints "Second", followed by the queueMicrotask() callback printing "Third".

This example demonstrates two important points:

  1. Microtasks do not interrupt the synchronous code that is already running.

  2. Microtasks scheduled during the same checkpoint are generally processed in queue order.

There is one more important detail: the runtime continues processing newly scheduled microtasks until the queue is empty, subject to the environment's scheduling rules.

Let's see what that means.

How Microtasks Can Schedule Other Microtasks

Consider this example:

console.log("Start");

Promise.resolve().then(() => {
  console.log("Microtask 1");

  queueMicrotask(() => {
    console.log("Microtask 3");
  });
});

Promise.resolve().then(() => {
  console.log("Microtask 2");
});

console.log("End");

Output:

Start
End
Microtask 1
Microtask 2
Microtask 3

Here's what happens:

  1. The synchronous statements print "Start" and "End".

  2. The first Promise handler executes and prints "Microtask 1".

  3. That handler schedules another microtask.

  4. The second Promise handler was already in the queue, so it prints "Microtask 2".

  5. The newly scheduled microtask then prints "Microtask 3".

The runtime does not stop processing microtasks just because one callback schedules another.

This behavior is important to understand when debugging Promise chains or code that uses queueMicrotask().

What Is a Macrotask?

A macrotask is a commonly used term for a regular event-loop task.

In browsers, tasks can be scheduled by timers, user interactions, message events, and other browser APIs.

For example, the following APIs can schedule tasks:

  • setTimeout()

  • setInterval()

  • User interaction events, such as click events.

  • Many message and I/O-related events.

The exact scheduling behavior depends on the API and the JavaScript environment.

Let's look at a basic timer example.

console.log("Start");

setTimeout(() => {
  console.log("Timer callback");
}, 0);

console.log("End");

Output:

Start
End
Timer callback

The timer callback does not execute immediately after setTimeout() is called.

Instead, the timer becomes eligible to run after the specified delay has elapsed, subject to browser scheduling rules. Its callback is then executed when the runtime selects the corresponding task and reaches it in the event loop.

This is why setting the delay to 0 does not mean the callback runs immediately.

Does setTimeout(fn, 0) Mean No Delay?

No. A zero-millisecond timer is not an instruction to execute the callback instantly.

It means the timer should become eligible as soon as the applicable timing rules allow.

For example:

console.log("Start");

setTimeout(() => {
  console.log("Timer executed");
}, 0);

const start = Date.now();

while (Date.now() - start < 1000) {
  // Simulate synchronous work.
}

console.log("End");

The output is:

Start
End
Timer executed

The while loop blocks JavaScript execution for approximately one second.

Even though the timer delay is zero, the timer callback cannot execute while the main JavaScript thread is busy running the loop.

This is an important lesson: asynchronous scheduling does not make synchronous JavaScript non-blocking.

If you perform expensive calculations on the main thread, timers, Promise callbacks, and browser interactions may all be delayed.

Microtasks vs. Macrotasks: What's the Difference?

Now that we understand both concepts, let's compare them directly.

Feature

Microtasks

Macrotasks (Tasks)

Common examples

Promise handlers, queueMicrotask()

Timer callbacks, click events, message events

When they execute

At a microtask checkpoint after current JavaScript execution

When the event loop selects the corresponding task

Scheduling priority

Processed before the next task at a browser microtask checkpoint

Selected according to the event loop and task scheduling rules

Queue behavior

Microtasks continue to be processed until the queue is empty

The event loop selects tasks as it progresses

Typical use

Handling Promise results and scheduling small follow-up operations

Timers, user interactions, and other event-driven work

Can block other work?

Yes, especially if microtasks keep being added

Yes, if a task runs lengthy synchronous code

One thing worth remembering is that the word priority can be misleading. Microtasks are not simply faster versions of timers.

They follow a different scheduling rule: in the browser, microtasks are processed at the relevant checkpoint before the event loop proceeds to another task.

If the microtask queue keeps receiving new work, it can delay timers, user interactions, and rendering opportunities.

Understanding the Event Loop

To understand why microtasks and tasks execute differently, we need to look at the JavaScript event loop.

JavaScript normally executes one piece of JavaScript code at a time on a given thread. When the current execution finishes, the runtime can process scheduled asynchronous work.

In a browser, the simplified process looks like this:

  1. JavaScript executes the current synchronous code.

  2. The runtime reaches a microtask checkpoint.

  3. The runtime processes queued microtasks until the queue is empty.

  4. The event loop selects another eligible task.

  5. After that task finishes, another microtask checkpoint occurs.

  6. The browser may perform rendering work at an appropriate opportunity.

This is a simplified explanation, not a complete description of the HTML event-loop specification. Rendering is not guaranteed to happen after every task, and different task sources can have different scheduling rules.

Let's see how this process works in practice.

console.log("A");

setTimeout(() => {
  console.log("B");

  Promise.resolve().then(() => {
    console.log("C");
  });
}, 0);

Promise.resolve().then(() => {
  console.log("D");
});

console.log("E");

Output:

A
E
D
B
C

Let's follow the execution order.

Step 1: Synchronous execution

The first two synchronous statements print:

A
E

The timer callback and Promise handler have been scheduled, but neither has executed yet.

Step 2: Process the initial microtask

The Promise handler prints:

D

Step 3: Execute the timer task

When the timer is eligible and selected, its callback prints:

B

Inside the timer callback, another Promise handler is scheduled.

Step 4: Process the new microtask

After the timer callback finishes, the runtime processes the newly queued Promise handler, which prints:

C

The final order is A, E, D, B, C.

Notice that the Promise callback scheduled inside the timer does not have to wait for every other timer to execute. It runs at the microtask checkpoint after the current task finishes.

This is a useful pattern to remember when a Promise is created inside a timer, event listener, or another callback.

What Happens When Microtasks Keep Getting Added?

Microtasks are processed until the queue is empty at the relevant checkpoint. This behavior is useful because Promise chains can finish processing their scheduled handlers before the runtime moves on to another task.

However, there is a downside.

If each microtask schedules another microtask indefinitely, the runtime may never reach the next task.

Consider this example:

function repeatMicrotask() {
  queueMicrotask(() => {
    console.log("Microtask running");

    repeatMicrotask();
  });
}

repeatMicrotask();

setTimeout(() => {
  console.log("Timer executed");
}, 0);

This code continuously adds new microtasks to the queue.

Because the queue never becomes empty, the runtime can remain busy processing microtasks instead of moving on to the timer task.

As a result, "Timer executed" may never be printed.

This is an example of microtask starvation.

It is similar to the event-loop starvation problem that can happen in Node.js when callbacks are continually added through process.nextTick().

How can we avoid microtask starvation?

Avoid continuously scheduling microtasks when the work could be divided into batches.

For example, in a browser environment, you could use a timer to schedule the next batch of work.

const items = Array.from({ length: 10000 }, (_, index) => index);

let index = 0;

function processBatch() {
  const batchSize = 100;
  const end = Math.min(index + batchSize, items.length);

  while (index < end) {
    // Replace this with your actual processing logic.
    const item = items[index];

    if (item < 0) {
      console.log("Invalid item");
    }

    index++;
  }

  if (index < items.length) {
    setTimeout(processBatch, 0);
  } else {
    console.log("All items processed");
  }
}

processBatch();

This example processes a limited number of items in each batch and schedules the next batch using a timer.

That gives the event loop opportunities to handle other eligible tasks between batches.

The exact timing depends on the environment, and timers do not guarantee immediate execution. For browser interfaces, requestAnimationFrame() or scheduler.yield() may be more suitable in certain situations, depending on the goal and browser support.

The important point is to avoid keeping the runtime busy indefinitely with one uninterrupted stream of work.

What Is the Difference Between Promises and queueMicrotask()?

Both Promise handlers and queueMicrotask() use microtask scheduling, but there is a practical difference in how errors are handled.

Consider a Promise handler:

Promise.resolve().then(() => {
  throw new Error("Something went wrong");
}).catch((error) => {
  console.error("Promise error:", error.message);
});

The thrown error rejects the Promise returned by .then(), and the .catch() handler can handle that rejection.

Now consider queueMicrotask():

queueMicrotask(() => {
  throw new Error("Something went wrong");
});

Here, the error is not converted into a rejected Promise. It is reported as an uncaught exception through the runtime's normal error-reporting mechanism.

This distinction matters when choosing how to schedule work.

Use Promise handlers when you're working with Promise-based operations and need Promise chaining or rejection handling.

Use queueMicrotask() when you specifically want to schedule a microtask without needing to create a Promise chain.

For example:

function updateState() {
  queueMicrotask(() => {
    console.log("State update scheduled");
  });
}

updateState();

This can be useful when a small operation needs to run after the current synchronous code finishes but before the runtime proceeds to another task.

However, avoid using microtasks for lengthy calculations. Microtasks still execute JavaScript on the same thread.

How Do Microtasks Work in Node.js?

The general idea of microtasks also applies to Node.js, but Node.js has some additional scheduling behavior that is important to understand.

For example, Node.js provides process.nextTick(), which uses a separate next-tick queue.

Consider this example in a typical CommonJS script:

console.log("Start");

process.nextTick(() => {
  console.log("Next tick");
});

Promise.resolve().then(() => {
  console.log("Promise");
});

setImmediate(() => {
  console.log("Immediate");
});

setTimeout(() => {
  console.log("Timer");
}, 0);

console.log("End");

A typical output is:

Start
End
Next tick
Promise
Timer
Immediate

However, the relative order of the timer and immediate callbacks is not guaranteed when both are scheduled from top-level code.

Let's look at the main differences.

process.nextTick()

Node.js processes process.nextTick() callbacks before continuing through normal event-loop phases at the relevant scheduling boundary.

In a typical CommonJS script, next-tick callbacks run before Promise microtasks scheduled at that boundary.

Promise handlers

Promise handlers are microtasks. They run after the current JavaScript execution finishes and are processed according to Node.js's microtask scheduling rules.

setImmediate()

setImmediate() schedules its callback for the check phase of the Node.js event loop.

It is not the same as a Promise microtask.

setTimeout()

setTimeout() schedules a timer callback that becomes eligible according to timer scheduling rules.

Its callback does not necessarily execute immediately when the specified delay expires.

These distinctions are particularly useful when debugging backend applications that rely on timers, streams, file system operations, and other asynchronous APIs.

If you're working with Node.js, remember that its event-loop behavior is related to browser JavaScript but not identical in every detail.

Common Mistakes Developers Make

When learning microtasks and tasks, there are a few mistakes worth avoiding.

1. Assuming setTimeout(fn, 0) runs immediately

A zero-delay timer still has to wait for the current synchronous execution to finish and for the timer to become eligible and be selected by the event loop.

2. Assuming every asynchronous callback is a microtask

Not all asynchronous callbacks are microtasks. Promise handlers and queueMicrotask() callbacks are microtasks, while timer callbacks are scheduled as tasks in browsers.

Node.js also has its own next-tick scheduling mechanism.

3. Thinking microtasks always make an application faster

Microtasks are processed before the event loop moves on to another task at the relevant checkpoint, but an excessive number of microtasks can delay other work.

4. Forgetting that synchronous code blocks everything else

A long-running loop can prevent timers, Promise callbacks, user interactions, and other scheduled JavaScript from executing until the loop finishes.

5. Assuming browser and Node.js scheduling are identical

Browsers and Node.js share many JavaScript concepts, but they have different event-loop implementations and additional scheduling rules.

When precise execution order matters, test your code in the environment where it will run.

When Should You Use Microtasks or Tasks?

There is no need to choose between microtasks and tasks manually for every asynchronous operation. Often, the API you're using determines the scheduling mechanism.

Still, understanding their differences helps you make better decisions.

Use Promise handlers when:

  • You need to process the result of an asynchronous operation.

  • You want to connect multiple asynchronous steps.

  • You need Promise-based error handling.

Use queueMicrotask() when:

  • You want to schedule a small callback after the current synchronous execution.

  • You need microtask scheduling without creating a Promise chain.

Use timers or other task-scheduling APIs when:

  • You want to defer work to a later task.

  • You need to divide a large amount of work into batches.

  • You want to give the event loop opportunities to process other work between batches.

For CPU-intensive calculations, consider a Web Worker in the browser or a worker thread in Node.js. Scheduling a callback with a timer or microtask does not move the calculation to another thread.

Conclusion

Microtasks and macrotasks are two important concepts for understanding asynchronous JavaScript.

Microtasks are used by Promise handlers and queueMicrotask(). In browsers, they are processed at microtask checkpoints before the event loop proceeds to another task.

Tasks, commonly called macrotasks in tutorials, include timer callbacks and many event-driven operations. The event loop selects eligible tasks according to its scheduling rules.

The key differences to remember are:

  • Synchronous JavaScript runs before queued callbacks.

  • Promise handlers and queueMicrotask() callbacks are processed as microtasks.

  • Timer callbacks are scheduled as tasks, not microtasks.

  • Microtasks are processed before the event loop proceeds to another task at the relevant browser checkpoint.

  • Continuously scheduling microtasks can starve timers and other work.

  • Node.js has additional scheduling behavior, including process.nextTick().

  • Neither microtasks nor tasks automatically move CPU-intensive work to another thread.

Once you understand how microtasks and tasks interact with the event loop, it becomes much easier to explain why callbacks execute in a particular order.

My recommendation is to practise these concepts with small examples using Promise.resolve(), queueMicrotask(), setTimeout(), and setImmediate() in Node.js. Predict the output before running each example, then compare your prediction with the actual result.

This is one of the best ways to build a practical understanding of JavaScript's asynchronous execution model.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘