Thursday, April 21, 2016

The Event Loop

Thursday, April 21 2016

Event Loop:
What is the event loop? The event loop describes the asynchronous mechanic by which Javascript prioritizes the callstack, render queue, task queue and web api's (c++ api's for node). For example, as web api's are called (with commands like .on, .get, setTimeout), they are placed in the task queue which are then run according to the order in which they were placed. Knowing of the event loop can help conceptualize the order of the callstack as well as asynchronous events! So lets dive into what is actually happening, and to do that, we first have to understand the call stack.

The Call Stack
The call stack is a data structure that records where in the code we are. Every single time we step into a function, we push onto the stack, while every time we return (step) out of a function, we pop it off. The stack is the order of functions that we run while the heap is the memory thats allocated for these operations.

So if we had:
function foo () {
   console.log('Hello');
   bar();
}
function bar () {
  console.log(' world!');
}
foo();

-our file (main) is pushed onto the call stack
-foo is pushed onto the call stack
-console.log('Hello') is pushed onto the call stack
-console.log('Hello') is popped off the call stack
-bar is pushed onto the call stack
-console.log(' world!') is pushed onto the call stack
-console.log(' world!') is popped off the call stack
-bar is popped off the call stack
-foo is popped off the call stack
-main is popped off the call stack

So the call stack is a single threaded, single stack that processes one thing at a time. However, this is a problem because we are working with the web, browsers, the network and databases, all of which may take a long time to load. For example, requesting the entire history of P-Diddy's tweets from the Twitter API takes some time to process. With the current call stack, our application would freeze until that data was successfully fetched. That would suck. So what's the solution? Asynchronous callbacks via web api's and the task queue.

The Event Loop (for real)
The event loop allows us to run stuff asynchronously even if the run time environment of V8 is only synchronous. How does this work? When we use some command like setTimeout, setInterval or some HTTP request, the task is given to the web api's while the rest of the code is run. Once the web API is finished it's then handed to the Task (callback) Queue, which then holds it until the stack is clear. Once the stack is clear, the task queue pushes the next queue'd item into the stack (one at a time).

A quick note about setTimeout: This is why setTimeout is not something that is guaranteed to run at the timeout that you give it. It is, instead, the minimum amount of time that is guaranteed to pass before the function is called. IE: at 0, the function is placed into the callback queue, while the stack is finished running. The stack could take longer than 0ms to run, thereby making the setTimeout run run a little bit after 0ms. The setTimeout isn't directed at the stack, it's directed at the web API. So setTimeout isn't "run this function in X ms", but rather "after X ms hand this callback/data to the callback queue after X ms".


The Render Queue
One last thing. For a proper user experience on our website, we want to aim for 60 frames per second. So how do we code with this in mind? Well the browser would like to rerender the page every 16.6 ms, meaning that if anything in the stack is taking longer than 16.6 ms to load, the fps will fail to be 60fps. (Why is 60 FPS important?) Similar to the callback queue, the render queue will refresh the page after the call stack is clear. This means that, if you're running some intensive process in the stack, it's better to hand it off to the web APIs for processing rather than leave it in the call stack for processing, because users will start to experience a dip in performance.

TLDR: The event loop is the mechanic responsible for asynchronous javascript. While V8 runs synchronously and javascript is single threaded, the combination of web API's and the callback queue allow multiple different processes to run simultaneously.

References:
http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop
http://www.tutorialspoint.com/nodejs/nodejs_event_loop.htm
https://www.youtube.com/watch?v=8aGhZQkoFbQ

No comments:

Post a Comment