SyntaxStudy
Sign Up
JavaScript Synchronous vs Asynchronous JavaScript
JavaScript Beginner 7 min read

Synchronous vs Asynchronous JavaScript

Synchronous vs Asynchronous JavaScript

JavaScript is single-threaded — it can only execute one piece of code at a time. Synchronous code runs line by line, and each line must complete before the next begins. This works fine for simple logic, but when a task takes time (reading a file, fetching data from a server), synchronous execution would freeze the entire application.

The Event Loop

JavaScript's concurrency model is built on an event loop. The engine runs the current call stack to completion, then checks a queue of pending tasks (callbacks, promises, timers) and processes them one at a time. This allows JavaScript to handle I/O without threads.

Blocking vs Non-blocking

Synchronous operations that take a long time are called blocking — they prevent any other code from running. Asynchronous operations register a callback or return a promise and yield control back to the event loop, which can handle other tasks while waiting.

Why It Matters

In browsers, blocking the main thread freezes the UI — animations stutter, clicks go unregistered, and scroll becomes unresponsive. In Node.js, blocking the thread means no other requests can be served. Asynchronous patterns solve both problems.

Example
console.log('1: start');
setTimeout(function() {
  console.log('3: async (after 0ms)');
}, 0);
console.log('2: end');
// Output order: 1, 2, 3
// Even with 0ms delay, setTimeout is async
function slowSync() {
  const end = Date.now() + 2000;
  while (Date.now() < end) {} // blocks for 2 seconds!
  return 'done';
}
// console.log(slowSync()); // freezes everything for 2s
fetch('https://api.example.com/data')
  .then(res => res.json())
  .then(data => console.log('data received'))
  .catch(err => console.error(err));
console.log('This runs before fetch completes');
Pro Tip

Always prefer asynchronous APIs for I/O tasks — even a 100ms synchronous network call will visibly freeze a browser UI and drop animation frames. Use fetch, async file APIs, and database drivers that return promises.