Why does JavaScript execute code in an unexpected order? Discover how the event loop works, learn to manage asynchronous operations, and build faster, more reliable applications through practical examples.
JavaScript Doesn’t Always Run in the Order You Expect
Here’s a simple JavaScript challenge.
Before reading further, predict what this code will display:
console.log("Start");
setTimeout(() => {
console.log("Timer");
}, 0);
Promise.resolve().then(() => {
console.log("Promise");
});
console.log("End");
You might expect the messages to appear in the order they’re written.
But the actual output is:
Start
End
Promise
Timer
Why does the Promise execute before the timer?
Why doesn’t setTimeout() run immediately when its delay is zero?
And how does JavaScript manage asynchronous operations when it normally executes code on a single main thread?
These questions lead to one of the most important concepts in modern JavaScript development: the event loop.
Understanding the event loop helps you write better code, debug confusing behavior, improve application performance, and work confidently with APIs, Promises, and async/await.
The good news is that asynchronous JavaScript becomes much easier to understand when you can experiment with it.
That’s why I’ve created the JavaScript Async & Event Loop Lab, a free DiscoveryVIP learning resource to explore these concepts through hands-on practice.
Explore the guide:
https://discoveryvip.com/javascript-async-event-loop-lab/
In this article, we’ll explore how JavaScript handles asynchronous execution, build practical examples, and develop a mental model you can apply to real projects.
1. What Does Asynchronous JavaScript Actually Mean?
JavaScript executes synchronous instructions in sequence.
Consider:
console.log("First");
console.log("Second");
console.log("Third");
The output is predictable:
First
Second
Third
Each instruction completes before the next begins.
But what happens when your application needs to wait for something?
For example:
- Downloading information from an API
- Waiting for a timer
- Reading a file
- Processing a user interaction
- Loading data from a server
If every operation blocked JavaScript until it finished, websites would frequently become unresponsive.
Asynchronous programming allows applications to initiate operations and continue doing other work while waiting for results.
Consider:
console.log("Loading data...");
setTimeout(() => {
console.log("Data ready!");
}, 2000);
console.log("User interface ready");
Output:
Loading data...
User interface ready
Data ready!
The timer doesn’t block the remaining synchronous instructions.
Instead, the browser schedules the callback to execute later.
Key concept: Asynchronous JavaScript coordinates operations that may complete at different times.
It doesn’t automatically mean that JavaScript code is running on multiple threads.
2. Understand the Call Stack
The call stack is where JavaScript tracks active function calls.
Consider:
function start() {
console.log("Starting");
processData();
}
function processData() {
console.log("Processing");
finish();
}
function finish() {
console.log("Finished");
}
start();
The execution sequence is:
start()enters the call stack.start()callsprocessData().processData()callsfinish().finish()completes.processData()completes.start()completes.
Only one function call is actively executing at a time on the main JavaScript thread.
This is why a long-running calculation can make a browser interface appear frozen.
For example:
let total = 0;
for (let i = 0; i < 100000000; i++) {
total += i;
}
console.log(total);
While this loop is executing on the main thread, the browser may be unable to respond promptly to user interactions.
Asynchronous scheduling helps with waiting operations, but it doesn’t automatically solve CPU-intensive work.
For that, technologies such as Web Workers may be appropriate.
3. Meet the Event Loop
The event loop coordinates when JavaScript can process scheduled work.
A useful simplified model includes:
Call Stack: Currently executing JavaScript.
Runtime APIs: Browser capabilities that manage operations such as timers and network requests.
Task Queues: Scheduled work, including timer callbacks and many events.
Microtask Queue: High-priority queued work such as Promise reactions.
Event Loop: The runtime mechanism that coordinates execution and scheduling.
Here’s the important part.
After the current JavaScript execution completes, the runtime processes queued microtasks before proceeding to another task.
That’s why Promise callbacks often run before timer callbacks.
Example
console.log("A");
setTimeout(() => {
console.log("B");
}, 0);
Promise.resolve().then(() => {
console.log("C");
});
console.log("D");
Output:
A
D
C
B
Let’s trace it.
Step 1: A is logged immediately.
Step 2: The timer callback is scheduled for a later task.
Step 3: The Promise reaction is queued as a microtask.
Step 4: D is logged immediately.
Step 5: The synchronous script finishes.
Step 6: The microtask logs C.
Step 7: The timer callback eventually logs B.
The result becomes understandable once you distinguish synchronous execution, microtasks, and tasks.
A Useful Mental Model
Run synchronous code → Process microtasks → Move to another task
This is a simplification of the browser event loop, which also coordinates rendering and other runtime activity, but it’s an excellent starting point.
4. Promises: Managing Future Results
A Promise represents the eventual result of an operation.
It can be:
- Pending: Not yet settled.
- Fulfilled: Completed successfully.
- Rejected: Failed.
Let’s create one.
const promise = new Promise((resolve) => {
setTimeout(() => {
resolve("Data loaded");
}, 1000);
});
promise.then((result) => {
console.log(result);
});
After approximately one second, the Promise fulfills and its reaction logs the result.
Promises are particularly useful when working with APIs and operations that may complete later.
A Subtle Detail About Promises
Consider:
const result = Promise.resolve(42);
result.then((value) => {
console.log(value);
});
console.log("Finished");
Output:
Finished
42
Even though the Promise is already fulfilled, its .then() callback doesn’t execute synchronously.
The callback is scheduled as a microtask.
This behavior is essential for understanding Promise execution order.
5. Async/Await: Making Asynchronous Code Easier to Read
The async and await keywords make Promise-based code easier to write and understand.
Consider:
function getUser() {
return Promise.resolve({
id: 1,
name: "Alex"
});
}
async function showUser() {
const user = await getUser();
console.log(user.name);
}
showUser();
The async keyword identifies an asynchronous function.
An async function always returns a Promise.
The await keyword allows you to work with the fulfilled result of a Promise.
But await doesn’t block the entire JavaScript thread.
Instead, it suspends the continuation of the async function while other JavaScript work can proceed.
Predict the Output
async function example() {
console.log("Inside 1");
await Promise.resolve();
console.log("Inside 2");
}
console.log("Outside 1");
example();
console.log("Outside 2");
The output is:
Outside 1
Inside 1
Outside 2
Inside 2
The async function begins executing immediately.
When it reaches await, its remaining work continues asynchronously.
Understanding this behavior makes debugging async/await significantly easier.
6. Sequential vs. Concurrent Execution
One of the biggest performance mistakes in asynchronous JavaScript is unnecessarily waiting for independent operations.
Imagine your application needs to load:
- User profile information
- Product recommendations
- Notifications
Here’s a sequential approach:
async function loadDashboard() {
const profile = await getProfile();
const products = await getProducts();
const notifications = await getNotifications();
return {
profile,
products,
notifications
};
}
Each operation waits for the previous one.
If they don’t depend on one another, this may waste time.
Instead, use Promise.all().
async function loadDashboard() {
const [
profile,
products,
notifications
] = await Promise.all([
getProfile(),
getProducts(),
getNotifications()
]);
return {
profile,
products,
notifications
};
}
Now the operations can make progress concurrently.
Example Timing
Suppose the operations take:
| Operation | Duration |
|---|---|
| Profile | 400 ms |
| Products | 800 ms |
| Notifications | 600 ms |
Sequential execution could take approximately 1,800 milliseconds.
Concurrent execution could take approximately 800 milliseconds, assuming independent operations and idealized timing.
The difference can be substantial.
However, concurrency isn’t always appropriate.
If the second operation requires data from the first, it must wait.
Good asynchronous programming means understanding dependencies—not simply using Promise.all() everywhere.
7. Choose the Right Promise Method
JavaScript provides several ways to coordinate multiple Promises.
Promise.all()
Use when every operation must succeed.
const results = await Promise.all([
fetchUser(),
fetchOrders(),
fetchSettings()
]);
If one rejects, the combined Promise rejects.
Other operations that have already started aren’t automatically cancelled.
Promise.allSettled()
Use when you need to know the outcome of every operation.
const results = await Promise.allSettled([
fetchUser(),
fetchOrders(),
fetchSettings()
]);
results.forEach((result) => {
console.log(result.status);
});
This is useful for batch operations where partial success is acceptable.
Promise.race()
Use when the first settled Promise determines the result.
const result = await Promise.race([
requestData(),
timeoutPromise()
]);
Be careful: racing a timeout against a request doesn’t automatically cancel the request.
Promise.any()
Use when you want the first successfully fulfilled Promise.
const result = await Promise.any([
fetchFromServerA(),
fetchFromServerB()
]);
If all inputs reject, the combined Promise rejects with an AggregateError.
Quick Reference
| Method | Behavior |
|---|---|
Promise.all() | Requires all operations to fulfill |
Promise.allSettled() | Reports every outcome |
Promise.race() | First settlement wins |
Promise.any() | First fulfillment wins |
Learning these methods helps you design better API workflows and more resilient applications.
8. Build a Working Asynchronous JavaScript Experiment
Let’s create a practical example that compares sequential and concurrent operations.
We’ll simulate three requests using Promises and timers.
function simulateRequest(name, delay) {
return new Promise((resolve) => {
console.log(`${name} started`);
setTimeout(() => {
console.log(`${name} completed`);
resolve(name);
}, delay);
});
}
Now create a sequential version.
async function runSequential() {
console.time("Sequential");
await simulateRequest("A", 500);
await simulateRequest("B", 800);
await simulateRequest("C", 300);
console.timeEnd("Sequential");
}
The operations complete one after another.
The simulated delays add up to approximately 1,600 milliseconds.
Now try a concurrent version.
async function runConcurrent() {
console.time("Concurrent");
await Promise.all([
simulateRequest("A", 500),
simulateRequest("B", 800),
simulateRequest("C", 300)
]);
console.timeEnd("Concurrent");
}
All three simulated requests begin without waiting for the previous request to finish.
The total time should be approximately 800 milliseconds, plus scheduling overhead.
Run the Experiment
Execute each function separately:
await runSequential();
Then:
await runConcurrent();
These calls can be used in a browser console that supports top-level await.
Alternatively, invoke them inside an async function.
Try These Challenges
Challenge 1: Change Request B to 2,000 milliseconds.
Challenge 2: Add a fourth request.
Challenge 3: Make one request reject.
Challenge 4: Replace Promise.all() with Promise.allSettled().
Challenge 5: Explain why concurrent execution can be faster even though JavaScript still executes callbacks one at a time on the main thread.
This is the kind of experimentation that turns theoretical knowledge into practical understanding.
9. Real-World Example: Fetch Data from an API
Asynchronous JavaScript is especially important when working with APIs.
The fetch() API allows browsers to make HTTP requests.
Consider:
async function loadUsers() {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users"
);
if (!response.ok) {
throw new Error(
`HTTP error: ${response.status}`
);
}
const users = await response.json();
console.log(users);
} catch (error) {
console.error(
"Unable to load users:",
error
);
}
}
loadUsers();
This example introduces several important concepts.
Awaiting fetch: Waits for the response.
Checking response.ok: Detects unsuccessful HTTP status responses.
Parsing JSON: Converts response data into a JavaScript value.
Handling errors: Prevents failures from going unnoticed.
One common misunderstanding is that fetch() automatically rejects when the server returns a 404 or 500 response.
It generally doesn’t.
You need to inspect the HTTP response status.
This distinction is essential for reliable applications.
10. Prevent Race Conditions in Interactive Applications
Imagine building a search interface.
A user types:
JavaScript
The application starts a search request.
Before the request finishes, the user types:
Python
The second request starts.
But what happens if the first request finishes last?
Without proper handling, your interface might display outdated JavaScript results even though the user is now searching for Python.
This is a race condition involving stale responses.
A Practical Solution
Use a request identifier.
let latestRequest = 0;
async function search(query) {
const requestId = ++latestRequest;
try {
const response = await fetch(
`/api/search?q=${encodeURIComponent(query)}`
);
if (!response.ok) {
throw new Error("Search failed");
}
const results = await response.json();
if (requestId !== latestRequest) {
return;
}
displayResults(results);
} catch (error) {
if (requestId !== latestRequest) {
return;
}
console.error(error);
}
}
Each new request receives an identifier.
Only the latest request is allowed to update the interface.
This is a practical technique for live search, autocomplete, dashboards, and dynamically loaded content.
Another useful tool is AbortController, which can request cancellation of supported operations.
The key lesson is that asynchronous operations don’t always finish in the order they start.
Your application needs to account for that.
11. Common Asynchronous JavaScript Mistakes
Mistake 1: Forgetting to Await a Promise
async function getNumber() {
return 10;
}
const value = getNumber();
console.log(value);
This logs a Promise, not the number 10.
Use await in an async context or .then() to access the fulfilled value.
Mistake 2: Using async with forEach()
items.forEach(async (item) => {
await processItem(item);
});
forEach() doesn’t wait for the Promises returned by its callbacks.
For sequential processing:
for (const item of items) {
await processItem(item);
}
For independent concurrent processing:
await Promise.all(
items.map((item) => processItem(item))
);
Mistake 3: Assuming setTimeout(fn, 0) Runs Immediately
A zero-delay timer schedules work for a later task.
It doesn’t interrupt synchronous execution.
Mistake 4: Ignoring Promise Rejections
Every important asynchronous operation should have an appropriate error-handling strategy.
Mistake 5: Running Too Many Requests at Once
Concurrency can improve performance, but excessive concurrency can overload services or hit rate limits.
For large batches, use a concurrency limit.
Mistake 6: Assuming Async Means Parallel
async doesn’t automatically move CPU-intensive code to another thread.
Mistake 7: Not Testing Unexpected Execution Orders
Always consider what happens if responses arrive late, fail, or complete in a different order.
12. Learn the Event Loop by Predicting the Output
One of the best ways to understand asynchronous JavaScript is to predict what a program will do before running it.
Try these three challenges.
Challenge 1: Promise vs. Timer
console.log("1");
setTimeout(() => {
console.log("2");
}, 0);
Promise.resolve().then(() => {
console.log("3");
});
console.log("4");
Question: What is the execution order?
Answer:
1
4
3
2
Challenge 2: Multiple Microtasks
console.log("A");
Promise.resolve().then(() => {
console.log("B");
});
queueMicrotask(() => {
console.log("C");
});
console.log("D");
Answer:
A
D
B
C
Both callbacks are microtasks, queued in that order.
Challenge 3: Async/Await
async function test() {
console.log("One");
await Promise.resolve();
console.log("Two");
}
console.log("Three");
test();
console.log("Four");
Answer:
Three
One
Four
Two
If you can explain why these results occur, you’re developing the mental model needed for more advanced asynchronous programming.
13. Use AI as an Asynchronous JavaScript Learning Coach
AI can be particularly useful when learning the event loop because it can help explain execution sequences and generate practice challenges.
However, the goal should be to develop your understanding rather than simply receive the correct answer.
Prompt 1: Event Loop Tutor
Act as an expert JavaScript instructor.
Teach me how the event loop works.
My current experience level:
[BEGINNER / INTERMEDIATE / ADVANCED]
Explain:
1. The call stack
2. Tasks
3. Microtasks
4. Promises
5. Async/await
6. Execution order
Provide a runnable JavaScript example.
Ask me to predict the output
before revealing the answer.
Then explain every execution step.
Prompt 2: Async Debugging Coach
Act as a senior JavaScript developer.
Help me debug this asynchronous code:
[PASTE CODE]
Expected behavior:
[DESCRIBE]
Actual behavior:
[DESCRIBE]
Investigate:
- Missing await
- Promise rejection
- Incorrect execution order
- Race conditions
- Stale responses
- Error handling
Explain the problem and
suggest the smallest reliable fix.
Provide a test to verify the solution.
Prompt 3: Async Performance Reviewer
Review this JavaScript code for
asynchronous performance issues.
[PASTE CODE]
Identify:
1. Unnecessary sequential operations
2. Independent requests
3. Appropriate Promise methods
4. Error-handling weaknesses
5. Potential race conditions
6. Concurrency limits
Suggest improvements without
changing the expected behavior.
Explain the tradeoffs.
Prompt 4: Interactive Challenge Generator
Create five JavaScript event loop challenges.
Include:
- Synchronous execution
- setTimeout
- Promises
- queueMicrotask
- async/await
Increase difficulty gradually.
For each challenge:
1. Show runnable code
2. Ask me to predict the output
3. Wait for my answer
4. Explain the correct order
5. Provide a follow-up experiment
These prompts encourage experimentation and understanding.
They also work well alongside an interactive JavaScript learning environment.
14. A Seven-Day JavaScript Async Learning Challenge
Here’s a practical roadmap for improving your asynchronous JavaScript skills.
Day 1 — Understand Synchronous Execution
Practice function calls and the call stack.
Predict the output of nested functions.
Day 2 — Explore Timers
Experiment with setTimeout() and setInterval().
Measure delays and observe execution order.
Day 3 — Learn Promises
Create fulfilled and rejected Promises.
Practice .then(), .catch(), and .finally().
Day 4 — Master Async/Await
Rewrite Promise chains using async/await.
Practice handling errors with try...catch.
Day 5 — Compare Concurrency Strategies
Use Promise.all() and Promise.allSettled().
Compare sequential and concurrent execution times.
Day 6 — Investigate the Event Loop
Predict the output of code combining synchronous statements, Promise reactions, and timers.
Explain each execution step.
Day 7 — Build an Async Application
Create an application that loads data from multiple sources.
Include:
- Loading indicators
- Error handling
- Concurrent requests
- Stale-response protection
- Clear user feedback
By the end of the challenge, you should be able to explain why asynchronous JavaScript behaves the way it does—not simply memorize its syntax.
15. Applying Vibe Learning to Asynchronous JavaScript
The event loop is an excellent example of why active learning matters.
Reading about microtasks and Promises is useful.
But real understanding develops when you predict execution, test your assumptions, inspect the results, and explain what happened.
This connects directly with the principles of Vibe Learning.
A practical learning cycle is:
Understand: Learn one asynchronous concept.
Predict: Decide what the code should do.
Build: Write a small example.
Test: Run the code.
Explain: Describe the execution order.
Reflect: Identify what surprised you.
Improve: Modify the example and try again.
For example, after learning how Promise callbacks work, add a timer.
Predict which callback runs first.
Then add another Promise inside a Promise callback.
Observe how microtasks are processed.
This approach transforms abstract concepts into observable behavior.
The goal isn’t to memorize the output of a few examples. It’s to understand JavaScript well enough to predict unfamiliar code.
16. Explore the JavaScript Async & Event Loop Lab
If you’re ready to develop a deeper understanding of asynchronous JavaScript, the next step is to experiment.
Explore execution order.
Practice working with Promises.
Compare async/await with Promise chains.
Investigate microtasks and timers.
Learn how concurrency affects performance.
Build applications that handle errors and unexpected responses reliably.
Explore the JavaScript Async & Event Loop Lab:
You can also explore the related JavaScript Async Lab, which includes 20 runnable challenges, a deterministic request-timing model, and event-loop prediction exercises.
Discover more free interactive JavaScript learning resources:
Explore the Vibe Learning framework:
Final Thoughts: Stop Guessing How JavaScript Works
Asynchronous programming is one of the most important skills in modern JavaScript development.
It affects how applications communicate with APIs, process information, respond to users, and coordinate operations.
Understanding Promises, async/await, tasks, microtasks, and the event loop gives you the ability to reason about behavior that might otherwise seem unpredictable.
It also helps you write faster, more reliable applications.
But the biggest improvement comes when you stop treating asynchronous JavaScript as a collection of syntax rules.
Instead, learn to think about execution.
What runs immediately?
What gets scheduled?
Which operations depend on others?
What happens when a request fails?
Can an older response overwrite newer information?
When you can answer these questions, asynchronous programming becomes much easier.
Predict the output. Run the experiment. Explain the result. Then build something useful.
That’s how you move from copying JavaScript examples to genuinely understanding how the language works.
About the Author
Laurence Svekis is a Google Developer Expert (Google Workspace), Google Champion, author, developer, and educator who has taught 3 million+ students through online courses and practical learning resources.
He is the creator of Vibe Learning and Vibe Teaching, approaches focused on active learning, experimentation, AI-assisted skill development, and meaningful understanding.
Through DiscoveryVIP.com and VibeLearning.ca, Laurence develops interactive learning tools, educational guides, and hands-on resources covering JavaScript, Google Apps Script, artificial intelligence, automation, and modern software engineering.