Home >Web Front-end >JS Tutorial >Event Loop — JavaScript

Event Loop — JavaScript

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-04 04:13:14480browse

Event Loop — JavaScript

Event loop is the loop that maintains the execution order (handling asynchronous operations without blocking the main thread) of JavaScript code.

Things to know before diving into event loop:

  1. Call Stack: This is where JavaScript executes our code. It follows a Last In, First Out (LIFO) structure. When a function is called, a new execution context is created and it gets pushed onto the stack. When the function ends, it’s popped off.
  2. MicroTasks Queue: Special queue dedicated to queueMicroTask methods, Promise handlers, await callbacks and MutationObserver (interface provides the ability to watch for changes being made to the DOM tree).
  3. MacroTasks Queue: All other callbacks from Web APIs (setTimeout, setInterval, DOM APIs, fetch) enters the macroTasks queue.

What is Event Loop?

It’s an endless loop that waits for tasks and pushes them into call stack for execution. Since JavaScript is single-threaded, it maintains an execution order to handle both synchronous asynchronous operations based on priority.

  1. Regular JS code: Synchronous code runs first and fills the call stack.
  2. MicroTasks: Tasks queued in microTasks queue gets executed.
  3. MacroTasks: Tasks queued in macroTasks queue gets executed.
// Programmatic way of how the event loop processes tasks
while (true) {
  // Step 1: Execute tasks in the call stack
  while (!callStack.isEmpty()) {
    const currentTask = callStack.pop();
    currentTask(); // Executes the task
  }
  // Step 2: Process all microtasks
  while (!microTasksQueue.isEmpty()) {
    const microTask = microTasksQueue.shift();
    callStack.push(microTask); // Push microtask to call stack for execution
  }
  // Step 3: Process one macrotask if available
  if (!macroTasksQueue.isEmpty()) {
    const macroTask = macroTasksQueue.shift();
    callStack.push(macroTask); // Push macrotask to call stack for execution
  }
  // Break if there's nothing left to process
  if (callStack.isEmpty() && microTasksQueue.isEmpty() && macroTasksQueue.isEmpty()) {
    break;
  }
}

Let’s go through an example to understand the workflow better

1.  setTimeout(() => console.log(1), 2000);
2.  Promise.resolve().then(() => {
3.      console.log(2);
4.      queueMicroTask(() => console.log(3));
5.  });
6.  Promise.resolve().then(() => {
7.      console.log(4);
8.      setTimeout(() => console.log(5));
9.  });
10. setTimeout(() => console.log(6));
11. console.log(7);

// 7 2 4 3 6 5 1

Let’s assume we have a 2 queues microTasks and macroTasks. When the code starts executing,

  1. () => console.log(1) gets pushed into the macroTasks queue in 2000ms.
  2. () => { console.log(2); queueMicroTask(() => console.log(3)); }) gets pushed into the microTasks queue.
  3. () => { console.log(4); setTimeout(() => console.log(5)); }) gets pushed into the microTasks queue.
  4. () => console.log(6) gets pushed into the macroTasks queue in 0ms.
  5. console.log(7) executes and prints 7 in console.
  6. Now the event loop checks the microTasks queue for tasks and takes () => { console.log(2); queueMicroTask(() => console.log(3)); }) task and prints 2 in console and pushes () => console.log(3) into microTasks queue.
  7. Next, the event loop checks microTasks queue and takes () => { console.log(4); setTimeout(() => console.log(5)); }) task and prints 4 and pushes () => console.log(5) into macroTasks queue in 0ms.
  8. Again, the event loop checks microTasks queue and takes () => console.log(3)) task and prints 3 in console.
  9. Since the microTasks queue is empty now, the event loop checks the macroTaskQueue and takes () => console.log(6) and prints 6 in console.
  10. Event loop takes the next task () => console.log(5) from the macroTasks after ensuring that there isn’t any tasks in microTasks queue and prints 5 in console.
  11. Event loop takes the next task () => console.log(1) from the macroTasks and prints 1 in console.

Thank you for reading! I hope you found this blog informative and engaging. If you notice any inaccuracies or have any feedback, please don’t hesitate to let me know.

The above is the detailed content of Event Loop — JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn