

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 8
click for more info
Not enough gems
Cost: 6 gems
1: Single Threaded
incomplete
2: Non Blocking
incomplete
3: The Call Stack
incomplete
4: Task Queue
incomplete
5: Microtask Queue
incomplete
6: Concurrency
incomplete
This lesson's interactive features are locked, please to keep using them
So how does JavaScript manage to be so efficient with asynchronous code? The answer is the event loop.
The event loop is a single-threaded, non-blocking, event-driven, asynchronous execution model.
Say that five times fast.
We already covered the single-threaded part, now let's grok non-blocking. Let's use this Python code as an example:
import time
print("Start")
time.sleep(2)
print("Middle")
time.sleep(2)
print("End")
This code prints "Start", then waits for 2 seconds, prints "Middle", waits another 2 seconds, and finally prints "End". The time.sleep(2) function calls are blocking: they stop the program's execution until 2 seconds have passed.
Let's write a similar example in JavaScript:
console.log("Start");
setTimeout(() => {
console.log("End");
}, 4000);
console.log("Middle");
This code prints "Start", then "Middle" immediately, waits 4 seconds, then prints "End". The main thread in JavaScript cannot be blocked. That's why setTimeout takes a callback function as an argument, it basically says:
Hey, I know I can't block the program, but please Mr. JavaScript engine, can you take this function and run it for me in 4 seconds?
So, the main thread should always be available to do work, and blocking (read: waiting) is delegated "for later".
A Go developer joined the Textio team and thought setTimeout would block execution like time.Sleep() in Go. It's possible, but slightly more complicated.
To await the result of sleep, the caller must be an async function.
The sleep helper function is a JavaScript staple.