My Take on…

“What the heck is the event loop anyway?”

V8 — the JavaScript interpreter inside Chrome is made up of 2parts:

1. Heap: where memory allocation happens

2. Call stack: the data structure which records at what point you are in a function. Since Javascript is a “single-threaded” language, it has one stack and can run one piece of code at a time.

When you step into the function, you place something into the stack. When you return that function, each individual step is then removed from the stack in the opposite order it was added.

When code is slow, it’s because the stack is being ‘blocked’.
ie: Things like image processing & network requests…

The solution is asynchronous programming — run some code, give it a call back and run it later…

There are 3 additional components that help asynchronous code get run:

1. Web APIs (things that live in the browser like the DOM, setTimeout, AJAX, etc…) These are threads that you can make calls to. This is what makes it concurrent.

2. Callback queue — the staging area of callback functions

3. Event loop — a loop which pushes code one at a time into the stack

The timeline of asynchronous programing:


1. When you call a setTimeout and pass a callback function it kicks off a timer in the browser. Meanwhile, the stack has been cleared and other lines of code can be run while the timer is counting down.

2. Once the timer is done, the web API pushes the code to the task queue which then goes to the… event loop.

3. The event loop looks at the stack and the task queue. If the stack is empty, it takes the first thing in the queue and pushes it on to the stack, which effectively runs it.

Setting the setTimeout to zero milliseconds technically defers something until the stack is cleared. The time argument you put in your setTimeout is not a guaranteed time to execution of the code, but instead a minimum time it will take for that code to push. So if you have slow code or several setTimeouts, the code still has to get processed by the browser, go into the queue and wait there until the call stack is cleared of the code that is running before it.

Without asynchronous programming, rendering of the page is also put on hold until the code is all run.

This is what people mean when they say “don’t block the event loop”… it means “don’t put slow code in the stack”. When you do that the browser can’t create a nice fluid UI.
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.