HomeToolsAbout a20k

Event Loop

Micro and Macro Task Queue

Micro-task Queue

Has higher priority than the Macro-task queue

e.g. Promises and Async functions

Promise async function

Macro-task Queue (just Task queue or Callback queue)

Runs when microtask queue is empty. Macro task moves into Call stack

e.g.

  • Browser APIs
  • UI rendering
  • .then() Callback functions after async/Promise
setTimeout() setInterval() setImmediate()

Event Loop Process

Event loop is something that constantly runs to handle functions across the tasks.

  • One go-around of event loop will have exactly one task processed from macrotask queue
    • Check the Macrotask queue
      • If the function is asynchronous, it is sent to the API module
        • Module pushes these tasks to macro-task queue after specified time
          • When added to macro-task, it must wait for the next cycle of Event loop to be evaluated
            • After that original macrotask completes, all available microtasks are processed
              • microtask can queue even more microtasks
                • when microtasks keep running and doesn't clear, it can lead to blocking fo UI rendering
            • In next cycle, function is passed to the Call stack
              • Call stack executes the function
                • When everything is empty, event loop waits for the next function to be added to the Call stack
© VincentVanKoh