Javascript Event Loop - Javascript Fundamentals

Again, welcome to Javascript Fundamentals (gameshow voice), where I recap my notes about… well, Javascript Fundamentals =)

This isn’t meant to be a lesson on the Javascript Event Loop – merely my regurgitation of thoughts and notes – so don’t expect eloquent paragraphs of enlightenment…

This video gives a great breakdown of the Javascript Event Loop.

Oh, and also see this article by Mozilla on the Javascript Event Loop

Screen Shot 2016-02-20 at 9.37.19 AM

  • JavaScript has a concurrency model based on an “event loop”
  • Stack: Function calls form a stack of frames (records the state of where we are in the program) - When a function is called/invoked/executed, a new local execution context (scope) is created containing it’s arguments and local variables. - The new local execution context also contains also contains a reference to the outer scope (scope chain)
  • The new local execution context also contains a ‘this‘ object is created (pointing to the object that invoked the function)
  • When another function is called/invoked/executed, a second local execution context (scope) is created and pushed on top of the first execution context. - The new local execution context also contains it’s own arguments and local variables, etc etc.
  • When the second function returns, the top execution context is popped off the stack.
  • When the first function returns, the stack is empty.
  • Heap: Objects are allocated in a heap (a large mostly unstructured region of memory).
  • Queue: A list of messages (each associated a function) to be processed that is in each Javascript runtime. - When the stack is empty, a message is taken out of the queue and processed (calling the associated function).
  • Calling the associated function creates an initial stack.
  • The message processing ends when the stack becomes empty again.
  • Event Loop:- Has one job – look at the stack and task queue.
  • If the stack is empty, it takes the first task on the queue and pushes it onto the stack.
  • DOM events (click, etc) or callbacks are pushed to queue

Interesting Points (from the video):

  • setTimeout is not a guaranteed time to execution, it’s the ‘minimum’ time to execution. - Due to the fact that setTimeout tasks are lined up in the event queue. See 18:11 marker in video.
  • Long-running (blocking) Javascript code can affect browser rendering. - Rendering is blocked when the call stack is not-empty, aka. “Don’t block the event loop”. See 20:14 marker in video.

Duncan Leung

Front End Developer at

Irvine, CA

Subscribe to Duncan Leung: Javascript and Front End Development

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!