theory.js

JavaScript's Concurrency Model

The Event Loop

JavaScript is single-threaded but handles asynchronous tasks using the event loop.

  • The event loop ensures non-blocking execution by managing async tasks.
  • Synchronous code runs first, followed by queued async tasks.
  • The event loop pulls tasks from the task queue when the call stack is empty.
console.log("Start");

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

console.log("End");

// Output:
// Start
// End
// Timeout (Runs last due to event loop)