Philip Roberts: Help, I'm stuck in an event loop

Orde Saunders' avatarPublished: by Orde Saunders

Philip Robers @philip_roberts was talking at Scotland.js about the event loop, these are my notes from his talk.

How does JavaScript actually work?  The documentation on how the runtime works is lacking.  Even V8 doesn't know much.

Heap + Stack is the implementation of ECMA.  This is V8.  Heap is memory and not very intersting.

The call stack

Can only do one thing at a time - this is the single threaded nature of JS.  You can put function calls on the top and take things off the top - can't alter the middle.  Return takes the current object off the stack and picks up the new top item.  You have seen the stack when you have an error - a stack trace.


What happens when things are slow.  Running a fuction is fast, disk takes longer, network may never even complete.  If we had a synchronous network call that never completed then the stack would be blocked forever.  This is a problem in a browser because it will completely lock the browser.

Rather than use threads the browser uses asynchronous call backs.    For example a setTimeout().  However, this doesn't work with a single threaded stack - where does the async code live?

Concurrency and the event loop

The browser can do more than one thing at a time, WebAPIs are a big part of this.  They live outside add async code into the task queue.  The even loop moves things from the task queue into the stack when the stack is empty.  This is why setTimeout(..., 0) works - the stack will complete before the event loop moves the code from the task queue into the stack.  If code (e.g. XHR) errors out in the WebAPI area it never gets to the queue and doesn't block the stack.

If you do while(true) the stack will be blocked and the queue will never clear.