FeaturedJavaScriptProgrammingWeb Development

JavaScript Event Loop Explained with Timers and Microtasks

6 Mins read
JavaScript Event Loop Explained with Timers and Microtasks

How JavaScript Schedules Work: A Practical Guide to the Event Loop

Why can a zero-delay timer run after a promise callback? Why does a long calculation make a page feel frozen? The answers lie in the JavaScript event loop: the scheduling model that coordinates synchronous code, asynchronous callbacks, timers, and rendering. Understanding it helps you predict execution order, diagnose UI stalls, and choose the right tool for deferred work.

This guide explains the call stack, task and microtask queues, and what setTimeout actually guarantees. It also offers runnable examples, practical debugging steps, and common pitfalls for browser-based JavaScript.

What the JavaScript Event Loop Does

JavaScript runs each piece of synchronous code to completion on a call stack. In a browser, the event loop coordinates that execution with queued work such as timer callbacks, user input, promise reactions, and rendering. It does not normally interrupt a running JavaScript function to run another callback.

When the stack becomes empty, the environment can process queued work. A useful simplified model for a browser is:

  1. Run a task, such as a script, timer callback, or event handler.
  2. When that task finishes, run pending microtasks until the microtask queue is empty.
  3. The browser may update the page and render a frame when appropriate.
  4. Choose another task and repeat.

This is a practical model, not a guarantee that the browser renders after every task. Rendering depends on browser scheduling and whether an update is needed. Also, JavaScript environments differ: Node.js has its own event-loop phases and scheduling details, so browser ordering examples should not be assumed to describe every Node.js case.

Tasks, Often Called Macrotasks

Browsers queue many callbacks as tasks. Developers often call these “macrotasks” to distinguish them from microtasks, although the HTML standard generally uses “task.” Examples include:

  • A timer callback scheduled with setTimeout or setInterval.
  • A user interaction handler, such as a click callback.
  • Some browser event and message callbacks.
  • Initial script execution.

Tasks are not all drawn from one simple, universal FIFO line. Browsers organize work into task sources and use scheduling rules to select tasks. For everyday reasoning, though, remember that a running task completes before another task callback begins, and that microtasks are processed at task boundaries.

Microtasks: Promise Callbacks and More

Microtasks are used for work that should run after the current JavaScript stack finishes, before the event loop moves on to another task. Promise handlers registered with .then(), .catch(), and .finally() run as microtasks. The queueMicrotask() function also queues one directly.

After a task completes, the browser performs a microtask checkpoint: it runs queued microtasks, including new microtasks added by other microtasks, until the queue is empty. This can delay the next task and a potential rendering opportunity.

Promise Reactions Run After Synchronous Code

console.log("A");

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

console.log("C");

The output is:

A
C
B

The promise is already fulfilled, but its handler does not run immediately. The current script finishes first; then the handler runs as a microtask.

setTimeout Execution Order: What “Zero Delay” Means

setTimeout(callback, 0) does not mean “run now” or “run exactly zero milliseconds later.” It requests that the callback become eligible after the specified delay. The callback still has to wait for the current task to finish and for the event loop to select its task. A busy main thread can delay it further.

For ordinary browser code, a timer callback scheduled during a task runs as a later task. Promise handlers queued in the current task run first, because the microtask checkpoint happens before the next task is selected.

console.log("Start");

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

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

console.log("End");

Typical browser output is:

Start
End
Promise
Timer

The synchronous statements run first. The promise reaction then runs at the microtask checkpoint. The timer callback runs later as a task. This explains the basic setTimeout execution order relative to a promise callback, but does not mean timers have precise deadlines.

Timer Delays Are Minimums, Not Deadlines

Actual timer timing depends on factors such as other JavaScript work, browser load, background-tab throttling, and timer nesting rules. A callback scheduled for a short delay may run much later. Use timers for scheduling a future callback, not as a precise clock or a reliable animation mechanism.

For visual animation, use requestAnimationFrame(), which asks the browser to call a function before a future repaint. For elapsed-time measurement, use an appropriate clock such as performance.now() rather than counting timer intervals.

Compare the Queues with a Runnable Example

This example puts synchronous code, a timer, a microtask, and a second microtask in one place:

console.log("1: synchronous");

setTimeout(() => {
  console.log("4: timer task");
}, 0);

queueMicrotask(() => {
  console.log("3: first microtask");

  queueMicrotask(() => {
    console.log("3b: microtask added by a microtask");
  });
});

Promise.resolve().then(() => {
  console.log("3a: promise reaction");
});

console.log("2: synchronous");

One expected browser output is:

1: synchronous
2: synchronous
3: first microtask
3a: promise reaction
3b: microtask added by a microtask
4: timer task

Both queueMicrotask() and the promise reaction queue microtasks. The first microtask adds another one, which is processed before the browser moves on to the timer task. The relative order of the first two microtasks here follows the order in which they were queued.

Practical Steps for Predicting Execution Order

When a callback-order question or bug is difficult to reason about, work through it systematically:

  1. Mark synchronous statements. Run them in source order until the current stack is empty.
  2. Label each scheduled callback. Identify promise reactions and queueMicrotask() calls as microtasks; identify timers and event callbacks as tasks.
  3. Track when work is queued. A callback cannot run before the code that schedules it reaches the relevant scheduling operation.
  4. Drain microtasks at the checkpoint. Include microtasks added by other microtasks.
  5. Consider the next task separately. A timer can be eligible but still wait for the event loop to select it.
  6. Check the environment. Browser APIs, Node.js scheduling, and test-runner behavior are not interchangeable.

For debugging, add temporary labels to logs and keep each callback identifiable. In browser developer tools, set breakpoints inside handlers and inspect the call stack. When working with network-driven code, remember that a response callback may run as a later task, while promise continuations attached to its result run as microtasks. Developers maintaining older AJAX code may also find FromDev’s guide to AJAX books for JavaScript developers useful background on asynchronous web requests.

Trade-Offs: Microtasks, Timers, and Rendering

Use Microtasks for Small Follow-Up Work

Microtasks are useful when a small operation should happen after the current stack, without waiting for another task. Promise chains and queueMicrotask() are common choices. They are not a way to make expensive work non-blocking: the callback still runs on the main thread.

Use Tasks to Yield to Other Work

A timer can defer work to a later task, giving the browser an opportunity to process other queued work between callbacks. But it does not guarantee that the browser will render before that timer runs, and repeated short timers are not a substitute for a well-designed scheduler.

Use Animation Scheduling for Visual Updates

For changes tied to the next visual frame, requestAnimationFrame() is usually a better fit than setTimeout(). It aligns the callback with browser rendering rather than asking for an arbitrary delay.

Common Event Loop Pitfalls

  • Assuming zero delay means immediate execution. A timer waits until its delay has elapsed and the event loop can run its callback.
  • Expecting a timer to beat a promise reaction. In the usual browser case, microtasks queued during the current task run before the next timer task.
  • Creating an endless microtask chain. A microtask that continually queues another microtask can prevent the queue from emptying, delaying tasks and rendering.
  • Blocking the main thread. A long loop or expensive synchronous calculation prevents input handling and rendering until it finishes.
  • Using timers as precise clocks. Scheduling delays and throttling make timer intervals unsuitable for precise timekeeping.
  • Assuming browser behavior applies everywhere. Node.js has a different event-loop model, so verify ordering in the runtime you actually use.

If a page becomes unresponsive, break expensive work into manageable chunks, use a Web Worker for suitable CPU-heavy tasks, or use an API designed for the job. Avoid yielding by recursively queuing microtasks: that keeps execution in the microtask checkpoint and may still starve the browser of a chance to handle other work.

Event Loop Knowledge and Safer Browser Code

Scheduling matters beyond performance. Event handlers can run after the user has changed the page, navigated away, or triggered another operation. Validate assumptions inside asynchronous callbacks, clean up listeners and timers when they are no longer needed, and avoid treating a deferred callback as proof that the surrounding state is unchanged.

For broader browser-security context, see FromDev’s explanation of browser exploitation tools. For link behavior and accessible navigation, its article on improving accessibility with javascript:void(0) for JavaScript links provides related guidance; in general, prefer semantic links or buttons over JavaScript-only link patterns.

Conclusion

The JavaScript event loop is easier to reason about when you separate synchronous execution, tasks, and microtasks. Synchronous code finishes first, microtasks run at the checkpoint, and a timer callback runs later when its task is selected—not at an exact promised instant. Keep microtasks short, use timers and animation callbacks for the jobs they suit, and verify runtime-specific behavior when precision matters. These habits make callback order more predictable and help keep browser applications responsive.

Leave a Reply

Your email address will not be published. Required fields are marked *