Understanding JavaScript Event Loop

Apr 7, 2025

JavaScript Event Loop and Asynchronous Programming Lecture

Introduction to JavaScript Runtime

  • JavaScript Engine Components:
    • Call Stack
    • Memory Heap (not shown in slides)
  • Additional Components:
    • Web APIs
    • Task Queue
    • Microtask Queue
    • Event Loop
  • Importance: Enables asynchronous task handling in JavaScript, which is single-threaded.

Call Stack

  • Manages execution of JavaScript code.
  • Example Execution:
    • console.log(1) creates and evaluates an execution context, logs 1.
    • console.log(2) does the same, logs 2.
    • Function calls create new execution contexts which are pushed to the call stack.
  • Handles one task at a time; long tasks can cause blocking.

Handling Long Running Tasks

  • Web APIs Role:
    • Offload tasks to the browser (e.g., network requests, user inputs, timers).
    • Provide asynchronous capabilities, either callback-based or promise-based.

Callback-Based Web APIs

  • Geolocation API Example:
    • getCurrentPosition method uses success and error callbacks.
    • Registers callbacks without blocking the call stack.
    • Tasks are offloaded to the browser, which handles them asynchronously.
  • Task Queue:
    • Holds callbacks and event handlers for future execution.
    • Event Loop checks for an empty call stack, then transfers tasks from the task queue.

Event Loop

  • Monitors the call stack and task queue.
  • Transfers tasks to the call stack when it's empty.

SetTimeout Example

  • Registers callback and delay with the Timer's API.
  • Execution occurs after delay when the call stack is empty.
  • Ensures that delays specified are only until task queue entry, not execution.

Promise-Based Web APIs

  • Microtask Queue:
    • Dedicated to then, catch, finally callbacks, async function bodies, queueMicrotask callbacks.
    • Prioritized by the event loop over the task queue.
  • Fetch Example:
    • Creates a promise object and initiates a network request.
    • Responses prompt promise handlers to be pushed to the microtask queue.

Handling Tasks and Microtasks

  • Microtasks can schedule more microtasks, potentially creating infinite loops.
  • Node.js provides a mechanism (maxTickDepth) to prevent infinite microtask loops.
  • Callback APIs can be promisified for better readability.

Quiz Example

  • Provided sequence illustrates how execution order is determined: 51342.
  • Demonstrates interaction between promises, setTimeout, and microtasks.

Summary

  • JavaScript is single-threaded; uses web APIs for asynchronous tasks.
  • Task Queue and Microtask Queue handle different types of callbacks.
  • Event loop prioritizes microtask queue.
  • Understanding execution flow helps in managing asynchronous JavaScript.
  • Encourages experimentation with setTimeout and queueMicrotask to solidify understanding.

Conclusion

  • Asynchronous JavaScript can be complex but playing with examples helps.
  • Reach out for questions and enjoy learning and coding.