Synchronous and Asynchronous JavaScript

Introduction

Synchronous code runs line by line—each line waits for the previous to finish. Asynchronous code schedules work for later (timers, network, disk) so the program stays responsive. JavaScript is single-threaded for your script logic; the runtime handles waiting in the background and runs your callbacks when ready.

Prerequisites

Synchronous Example

javascript
// Each line blocks until done
function add(a, b) {
  return a + b;
}
 
const sum = add(2, 3);
console.log(sum);
console.log("done");

Order is always: 5, then "done".

Asynchronous with setTimeout

javascript
// Callback runs after sync code finishes
console.log("A");
 
setTimeout(() => {
  console.log("B");
}, 0);
 
console.log("C");

Typical output: A, C, B—even with 0 ms delay.

Why Async Exists

Blocking the main thread freezes UIs and slows servers handling many connections. Async lets you:

  • Respond to clicks while fetching data
  • Accept new HTTP requests while waiting on databases
  • Compose Promises without nested callback pyramids

Callback Style (Recap)

javascript
// Simulated delayed fetch
function fetchUser(id, callback) {
  setTimeout(() => {
    callback(null, { id, name: "Ada" });
  }, 100);
}
 
fetchUser(1, (err, user) => {
  if (err) return console.error(err);
  console.log(user.name);
});

Hard to read when nested deeply—Promises and async/await improve structure.

Event Loop (High Level)

  1. Run synchronous code until the stack is empty
  2. Process microtasks (Promise reactions)
  3. Process one macrotask (timer, I/O callback)
  4. Repeat

You do not schedule threads manually in browser JS—understand ordering to avoid race bugs.

Fake Sync vs Async API

javascript
// sync: returns value immediately
function readConfigSync() {
  return { theme: "dark" };
}
 
// async: result later via callback/Promise
function readConfigAsync(done) {
  setTimeout(() => done({ theme: "dark" }), 50);
}
 
console.log(readConfigSync());
readConfigAsync((cfg) => console.log(cfg));

Mini Example: Button + Delayed Log (Browser)

javascript
// Pattern for UI — run in browser console with a button element
function onClick() {
  console.log("clicked");
  setTimeout(() => console.log("after paint/work"), 0);
  console.log("handler end");
}
 
// onClick() simulates: clicked, handler end, after paint/work
onClick();

FAQ

Is JavaScript multithreaded?

User code runs on one main thread; Web Workers and Node worker threads are separate—advanced topic.

Async means parallel?

Not always—often concurrent scheduling on one thread, with true parallelism only via workers.

await blocks the thread?

It pauses the async function, not the whole program—other callbacks still run.

What comes next?

Promises.