🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEjavascript

javascript Documentation

LOADING ENGINE...

Event Loop

AI & DATA SCIENCE // event-loop

The event loop coordinates JavaScript's single thread: it processes the call stack first, then microtasks (Promises), then macro-tasks (setTimeout).

Syntax

// Execution order:
console.log('1 sync');
setTimeout(() => console.log('4 macro'), 0);
Promise.resolve().then(() => console.log('3 micro'));
console.log('2 sync');

Deep Dive Course

JavaScript is **single-threaded** — one operation at a time. The **event loop** enables concurrency via queues: (1) synchronous code runs on the **call stack**, (2) **microtask queue** (Promise .then, queueMicrotask) drains COMPLETELY after each stack task, (3) **macrotask queue** (setTimeout, setInterval) runs one task at a time.

1Understanding Event Loop

JavaScript is single-threaded — one operation at a time. The event loop enables concurrency via queues: (1) synchronous code runs on the call stack, (2) microtask queue (Promise .then, queueMicrotask) drains COMPLETELY after each stack task, (3) macrotask queue (setTimeout, setInterval) runs one task at a time.

💡

Microtasks (Promises) always run before the next macrotask (setTimeout). This is why Promise.resolve().then() runs before setTimeout(fn, 0).

editor.html
console.log('1: Start');

setTimeout(() => console.log('5: setTimeout'), 0);

Promise.resolve()
  .then(() => console.log('3: Promise 1'))
  .then(() => console.log('4: Promise 2'));

console.log('2: End');

// Output order: 1, 2, 3, 4, 5
localhost:3000

2Practical Example

Here is a real-world application of Event Loop showing how it is used in production JavaScript code.

editor.html
// Blocking the event loop
function longTask() {
  const start = Date.now();
  while (Date.now() - start < 3000) {} // blocks for 3 seconds!
  console.log('Done (but UI was frozen!)');
}

// Better: use Web Workers for CPU tasks
const worker = new Worker('./compute.js');
worker.postMessage({ task: 'heavyComputation' });
localhost:3000

3Best Practices

Follow these guidelines when working with Event Loop:

1. Don't block the event loop with long synchronous code

2. Use Web Workers for CPU-intensive tasks

3. Use requestAnimationFrame for smooth animations

⚠️

Tip: Microtasks (Promises) always run before the next macrotask (setTimeout). This is why Promise.resolve().then() runs before setTimeout(fn, 0).

editor.html
console.log('1: Start');

setTimeout(() => console.log('5: setTimeout'), 0);

Promise.resolve()
  .then(() => console.log('3: Promise 1'))
  .then(() => console.log('4: Promise 2'));

console.log('2: End');

// Output order: 1, 2, 3, 4, 5
localhost:3000

Examples

Example 01Basic Usage
console.log('1: Start');

setTimeout(() => console.log('5: setTimeout'), 0);

Promise.resolve()
  .then(() => console.log('3: Promise 1'))
  .then(() => console.log('4: Promise 2'));

console.log('2: End');

// Output order: 1, 2, 3, 4, 5
Example 02Advanced Example
// Blocking the event loop
function longTask() {
  const start = Date.now();
  while (Date.now() - start < 3000) {} // blocks for 3 seconds!
  console.log('Done (but UI was frozen!)');
}

// Better: use Web Workers for CPU tasks
const worker = new Worker('./compute.js');
worker.postMessage({ task: 'heavyComputation' });

Best Practices

  • Don't block the event loop with long synchronous code
  • Use Web Workers for CPU-intensive tasks
  • Use requestAnimationFrame for smooth animations

Interview Question

What is the difference between the microtask queue and the macrotask queue?

Hint: Priority and draining behavior.

The microtask queue (Promises, queueMicrotask, MutationObserver) is drained COMPLETELY after each synchronous task, before the event loop picks the next macrotask. The macrotask queue (setTimeout, setInterval, setImmediate) runs ONE task per event loop iteration. So Promise handlers always run before the next setTimeout, even with a 0ms delay.

Exercises

MediumPractice using Event Loop in a real scenario.
View Solution
console.log('1: Start');

setTimeout(() => console.log('5: setTimeout'), 0);

Promise.resolve()
  .then(() => console.log('3: Promise 1'))
  .then(() => console.log('4: Promise 2'));

console.log('2: End');

// Output order: 1, 2, 3, 4, 5

Frequently Asked Questions

What is the difference between the microtask queue and the macrotask queue?

The microtask queue (Promises, queueMicrotask, MutationObserver) is drained COMPLETELY after each synchronous task, before the event loop picks the next macrotask. The macrotask queue (setTimeout, setInterval, setImmediate) runs ONE task per event loop iteration. So Promise handlers always run before the next setTimeout, even with a 0ms delay.

Related Functions

PromisessetTimeoutsetIntervalCallback-Functions