My Take on…
“What the heck is the event loop anyway?”
1. Heap: where memory allocation happens
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:
WEB API (Timer)(1) > TASK QUEUE(2) > EVENT LOOP(3) > STACK
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.