The JavaScript Event Loop — How Async Code Actually Works

Understand the JavaScript event loop, call stack, task queue, and microtask queue with clear diagrams and examples.

JavaScript Advanced 📖 11 min

Why the Event Loop Exists

JavaScript is single-threaded — it has one call stack and one thread of execution. The event loop is the mechanism that allows JavaScript to perform non-blocking operations despite being single-threaded.

Microtasks vs Macrotasks

console.log('Start');
setTimeout(() => console.log('Timeout'), 0);
Promise.resolve().then(() => console.log('Promise'));
console.log('End');

// Output: Start, End, Promise, Timeout
// Promises (microtasks) have higher priority than setTimeout (macrotasks)

requestAnimationFrame

function animate() {
  element.style.transform = `translateX(${position}px)`;
  if (position < 500) requestAnimationFrame(animate);
}
requestAnimationFrame(animate);

Practical Patterns

// Debouncing
function debounce(fn, delay) {
  let timeoutId;
  return function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn.apply(this, args), delay);
  };
}

// Throttling
function throttle(fn, limit) {
  let inThrottle = false;
  return function(...args) {
    if (!inThrottle) {
      fn.apply(this, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

Key Takeaways

  • JavaScript is single-threaded but non-blocking
  • Microtasks (Promises) have higher priority than macrotasks (setTimeout)
  • Use requestAnimationFrame for smooth animations
  • Use requestIdleCallback for low-priority background work

Ready to Level Up Your Coding Skills?

Join Coderz Club and learn to code with challenges, battles, and an AI mentor.

Join Coderz Club Free →