What’s the Event Loop?
Some events do happen synchronously in JS. Loops will run in the call stack and prevent a webpage from re-rendering until they have completed.
However, due to the event loop built into browsers, processes such as AJAX requests and timeouts can run in the background, with their callback functions placed in a queue that are added to the call stack only when the entire stack has cleared. The below code snippet illustrates this.
If you paste this in your console, you’ll see 1 logged, then 2 returned, then 3 logged. Here’s what happens:
- The eventLoop function gets added to the call stack.
- The setTimeout timer begins and the callback function is added to the queue after 0 milliseconds.
- The number 1 is immediately logged.
- The eventLoop function returns 2 and the call stack is cleared.
- The setTimeout callback runs, logging 3.
Note that the call stack runs functions in ‘first in last out’ order (meaning that the first function added to a stack is the last to run). That’s why, in the code below, the strings are already concatenated when logged:
First, the greet function is added to the call stack. Then, the concat function is added to the call stack. Concat runs, the greeting is logged, and the greet function is cleared from the stack.
Meanwhile, the queue runs callback functions in ‘first in first out’ order. The first item added to the queue is the first to be added to the call stack. That means, if multiple AJAX requests are made, for instance, the first request to finish will be the first to have its callback function run.
- Philip Roberts – What the Heck is an Event Loop anyway?
- MDN – Concurrency Model and Event Loop
- Wikipedia – Event Loop