Skip to main content

Command Palette

Search for a command to run...

Synchronous vs Asynchronous JavaScript

Updated
•6 min read•View as Markdown
K
Hi, I'm Kanishka Shashi. I'm a Computer Science (AI & ML) student passionate about building, analyzing, and explaining technology. This blog is where I simplify complex concepts into practical, beginner-friendly guides. You'll find articles on Web Development, System Design, AI & LLMs, Data Analytics, SQL, Git/GitHub, and software engineering best practices. I enjoy exploring how modern technologies work under the hood and sharing insights through real-world examples and hands-on projects. Whether you're a student, developer, or tech enthusiast, I hope these articles help you learn something new and build better software. Learning in public. Building consistently. Sharing everything I discover.

When you start learning JavaScript, everything seems simple—code runs line by line, top to bottom. But as soon as you deal with real-world tasks like API calls, timers, or file handling, things become a bit more complex.

That’s where synchronous and asynchronous programming come into play.

Understanding this concept is super important for interviews, real-world projects, and writing efficient JavaScript code.

In this blog, we’ll cover:

  • What synchronous code means

  • What asynchronous code means

  • Why JavaScript needs async behavior

  • Real-world examples like API calls and timers

  • Problems with blocking code

  • Simple diagrams to make everything clear


🔹 What is Synchronous JavaScript?

Synchronous code executes line by line, one step at a time.

👉 It means the next line of code will not execute until the current line finishes.


✅ Simple Example

console.log("Step 1");
console.log("Step 2");
console.log("Step 3");

🔍 Output

Step 1
Step 2
Step 3

✔️ The execution is predictable ✔️ Each step waits for the previous one


🔍 Diagram Idea: Synchronous Execution Timeline

Time →
[Step 1] → [Step 2] → [Step 3]

💡 Real-Life Example

Imagine you're standing in a queue at a bank 🏦:

  • You wait for the first person

  • Then the second

  • Then your turn

👉 You cannot skip ahead. This is synchronous behavior.


🔹 What is Asynchronous JavaScript?

Asynchronous code allows tasks to run in the background without blocking the main execution.

👉 It means JavaScript can start a task and move on without waiting for it to finish.


✅ Example with setTimeout

console.log("Start");

setTimeout(() => {
  console.log("Inside Timeout");
}, 2000);

console.log("End");

🔍 Output

Start
End
(After 2 seconds)
Inside Timeout

🔍 Diagram Idea: Asynchronous Execution

Start → setTimeout → End
                ↓
          (after delay)
          Inside Timeout

💡 Real-Life Example

Imagine ordering food online 🍕:

  • You place the order

  • You don’t just sit and stare at the app

  • You do other work while the food is being prepared

👉 That’s asynchronous behavior.


🔹 Why JavaScript Needs Asynchronous Behavior

JavaScript is single-threaded, meaning it can do only one thing at a time.

So what happens if a task takes too long?

👉 It would block everything else.


❌ Example of Blocking Code

function longTask() {
  let start = Date.now();
  while (Date.now() - start < 5000) {
    // blocking loop for 5 seconds
  }
}

console.log("Start");
longTask();
console.log("End");

🔍 Output

Start
(wait 5 seconds)
End

❌ The UI freezes ❌ User experience becomes bad


🚀 Solution: Asynchronous Programming

Instead of blocking:

  • Run long tasks in the background

  • Continue executing other code


🔹 Blocking vs Non-Blocking Code


🔴 Blocking (Synchronous)

  • Stops execution until task completes

  • Slower performance

  • Bad for user experience

Task A → Wait → Task B → Wait → Task C

🟢 Non-Blocking (Asynchronous)

  • Doesn’t stop execution

  • Faster and efficient

  • Better for real-world apps

Task A → Task B → Task C
     ↓
   Background Task completes later

🔹 Real-World Examples of Asynchronous Code


✅ 1. API Calls

console.log("Fetching data...");

fetch("https://jsonplaceholder.typicode.com/posts")
  .then(response => response.json())
  .then(data => console.log(data));

console.log("Other work...");

👉 The app doesn’t wait for data—it continues running.


✅ 2. Timers

setTimeout(() => {
  console.log("Runs after 3 seconds");
}, 3000);

✅ 3. User Interactions

button.addEventListener("click", () => {
  console.log("Button clicked");
});

👉 JavaScript waits for the event but doesn’t block execution.


🔹 How JavaScript Handles Asynchronous Code

JavaScript uses something called:

  • Call Stack

  • Web APIs

  • Callback Queue

  • Event Loop


🔍 Diagram Idea: Async Task Queue Concept

Call Stack        Web APIs        Callback Queue
   |                  |                 |
   | setTimeout() →   |                 |
   |                  | → Timer done →  |
   |                  |                 ↓
   | ← Event Loop picks and executes callback

💡 Simple Explanation

  1. Code runs in the call stack

  2. Async tasks go to Web APIs

  3. Once done, they move to queue

  4. Event loop pushes them back to execution


🔹 Step-by-Step Example

console.log("1");

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

console.log("3");

🔍 Output

1
3
2

🤔 Why?

Even though delay is 0:

  • setTimeout is still asynchronous

  • It goes to queue first

  • Runs after the main code


🔹 Problems with Synchronous (Blocking) Code


❌ 1. Freezing UI

If heavy tasks run synchronously:

  • Page becomes unresponsive

  • Users get frustrated


❌ 2. Poor Performance

Blocking code:

  • Delays everything

  • Reduces efficiency


❌ 3. Bad User Experience

Users expect:

  • Fast response

  • Smooth interaction

Blocking breaks that expectation.


🔹 Advantages of Asynchronous Code


✅ 1. Better Performance

Multiple tasks handled efficiently.


✅ 2. Smooth User Experience

No freezing or delays.


✅ 3. Efficient Resource Usage

CPU is not wasted waiting.


🔹 When to Use Synchronous vs Asynchronous


Use Synchronous When:

  • Tasks are simple and fast

  • Order matters strictly


Use Asynchronous When:

  • Working with APIs

  • Handling timers

  • File operations

  • User interactions


🔹 Best Practices

✔️ Avoid long blocking operations ✔️ Use async features like:

  • setTimeout

  • fetch

  • async/await

✔️ Break large tasks into smaller chunks

✔️ Always handle async errors properly