

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 10
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
We understand the call stack: call a function, it's pushed onto the stack, when it returns, it's popped off. But what about asynchronous code?
Enter the task queue.
The task queue (also known as the "message queue") is where asynchronous tasks are queued up to be processed. It's just a standard queue of things for our JS engine to do, nothing to be scared of. But remember: JS is non-blocking, so the tasks in the queue can't be handled immediately.
The rule of the task queue is simple: when the call stack is empty, the event loop (managed by the JS runtime) checks the task queue. If there are tasks in the queue, it pushes the first one onto the call stack to be executed. Take a look at this example again:
function startJob() {
setTimeout(() => {
console.log("Hi I'm async!");
}, 0);
console.log("Job started");
workOnJob();
}
function workOnJob() {
console.log("Working on job");
finishJob();
}
function finishJob() {
console.log("Job finished");
}
startJob();
Because the setTimeout says "run this 0 milliseconds from now", you might expect its callback to run instantly and produce this output:
Hi I'm async!
Job started
Working on job
Job finished
But this is what actually happens:
Job started
Working on job
Job finished
Hi I'm async!
Because the callback:
() => {
console.log("Hi I'm async!");
};
Runs after the call stack is empty. That means finishJob, workOnJob, and startJob must all return before the callback can run.
Textio needs to process messages while leaving the main thread available to handle other requests. The starter processes only the first batch.
Complete processMessages. The provided processBatch helper processes up to batchSize messages starting at startIndex and returns the index of the next unprocessed message.
The expected output is:
Main thread: starting message processing
Processed batch: you're hired, standup in 5, deploy failed
Main thread: ready to handle another request
Processed batch: deploy fixed, pizza's here