Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created September 20, 2016 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/77fac5b24a7861a16f1b502705a15cc4 to your computer and use it in GitHub Desktop.
Save JoshCheek/77fac5b24a7861a16f1b502705a15cc4 to your computer and use it in GitHub Desktop.
JavaScript's event queue

I thought of a fourth linked list in JavaScript: the event queue, which enables asynchronousity. When I realized it must exist, a lot of things finally made sense.

The event queue is a queue of code to be run, it can also contain values to inject (eg the response from an HTTP request). Then, whenever JS finishes executing a piece of code, it dequeues the next bit of work and runs that code. If it runs out of work, it waits for something to enter the queue.

When people in JS talk about "blocking", they mean that you are doing a lot of work in one piece of code. Since it can only execute one at a time (single threaded), this means that the work in the queue isn't getting processed.

This increases latency, events like mouse clicks aren't doing whatever they're supposed to do, the page is non-responsive (which, to a user, means it's broken). This is why there is a setTimeout, but no sleep. It's why your code immediately returns from an HTTP request and you cannot make a loop to wait for the HTTP request to complete and run the callback: it would block the queue where the callback is waiting to be run. If you ever see a setTimeout of 0 seconds, the purpose is to add a callback to this queue.

If JS could store a callstack along with the code in this queue, then the interpreter could pause execution for later. This would allow users to write synchronous code that executed asynchronously, which would obviate the need for promises, generators, and many of the uses of callbacks. It would even be backwards compatible, if you use a function with its current interface, it behaves as it currently does. But if you omit the callback, then the callback becomes "resume execution, returning the data that would have been passed to the callback".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment