

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 4
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
Click to play video
So, we know that JavaScript has one main thread, and that it's non-blocking. So how do these "background" tasks (like HTTP requests, setTimeout, etc.) get executed? Well, it's via the event loop - but first, we need a little refresher on the call stack.
This next bit assumes you know about stacks, heaps, and the call stack. If you don't, review our memory management course first. That said, I'll give you a quick refresher. Every time a function is called, it gets added to the top of the call stack. When the function returns, it gets popped off the stack.
Let's say we have this code:
function startJob() {
console.log("Job started");
workOnJob();
}
function workOnJob() {
console.log("Working on job");
finishJob();
}
function finishJob() {
console.log("Job finished");
}
startJob();
The call stack will grow like this as each function is called:
-> finishJob
-> workOnJob workOnJob
[empty] -> startJob startJob startJob
Then as each function returns, it gets popped off the stack:
finishJob ->
workOnJob workOnJob ->
startJob startJob startJob -> [empty]
Long story short - JavaScript's call stack works the same way as any other language's call stack. But what happens when we encounter asynchronous code? We'll cover that in the next lesson.