Synchronous vs Asynchronous JavaScript
JavaScript is single-threaded — it can only do one thing at a time. Synchronous code runs line by line, blocking everything. Asynchronous code lets long operations (API calls, timers, file reads) run in the background without freezing the page.
Sync vs Async
- Synchronous — Code runs line by line. Each line waits for the previous to finish. Blocks everything
- Asynchronous — Long operations run in the background. Code continues executing. Results arrive later
- Why async? — Network requests take time. Without async, your page would freeze during every API call
- Single-threaded — JavaScript has ONE call stack. But the browser has Web APIs (timers, fetch) that run in parallel
- Analogy — Sync = waiting in line at a restaurant. Async = ordering and getting a buzzer, do other things until food is ready
Sync vs Async Code
// Synchronous — each line waits
console.log("1. Start"); // runs first
console.log("2. Processing..."); // waits for #1
console.log("3. Done"); // waits for #2
// Output: 1, 2, 3 (in order, predictable)
// Asynchronous — some operations run in background
console.log("1. Start");
setTimeout(() => console.log("2. Timer done"), 2000); // runs after 2 seconds
console.log("3. Continue"); // doesn't wait for timer!
// Output: 1, 3, 2 (3 runs before 2!)
// Real-world problem without async:
// Imagine fetching user data synchronously...
// The page would FREEZE for 2-3 seconds during every API call!
// Users can't click, scroll, or interact. Terrible UX.
// With async:
// fetchUserData() runs in background
// Page remains interactive
// When data arrives, callback/promise handles it
console.log("Start");
// Simulating async API call
setTimeout(() => {
console.log("Data received from API!");
}, 1500);
console.log("Page is still interactive...");Tip
Tip
JavaScript handles long tasks through the event loop — setTimeout, fetch, and DOM events are all managed by the browser and pushed back to JS when ready. Understanding this explains why async patterns exist.
Async code runs non-blocking — callbacks, promises, and async/await
Common Mistake
Warning
Assuming setTimeout(fn, 1000) will run exactly after 1 second. The delay is a minimum, not a guarantee. If the call stack is busy, the callback waits in the queue until the stack is empty.
Practice Task
Note
Visualize async: (1) console.log('1'); setTimeout(() => console.log('2'), 0); console.log('3'). Predict the output order (1, 3, 2). (2) Explain why '2' comes last even with 0ms delay.
Quick Quiz
Key Takeaways
- JavaScript is single-threaded — it can only do one thing at a time.
- Synchronous — Code runs line by line. Each line waits for the previous to finish. Blocks everything
- Asynchronous — Long operations run in the background. Code continues executing. Results arrive later
- Why async? — Network requests take time. Without async, your page would freeze during every API call