Middle+
Why does the log about 1 second appear first, and then about 2 seconds, when calling sleep(2000) and sleep(1000) twice? Explain the operation of the Event Loop, micro-tasks, and macro-tasks.
sobes.tech AI
Answer from AI
In JavaScript, timers such as setTimeout or sleep (if implemented via promises) work asynchronously and place tasks in the event queue (Event Loop).
When sleep(2000) and sleep(1000) are called, both start timers, but the second (1000 ms) will finish earlier than the first (2000 ms). When a timer expires, its callback function is placed in the macro task queue.
The Event Loop works as follows:
- Executes the current call stack.
- After the stack is clear, it takes tasks from the macro task queue and executes them one by one.
- After executing macro tasks, it runs all microtasks (like promises).
In this case:
sleep(1000)will finish earlier, its callback will be queued and executed first.sleep(2000)will finish later, its callback will execute afterwards.
Thus, the log with 1 second delay appears before the one with 2 seconds.
Example with promises and timers:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function test() {
sleep(2000).then(() => console.log('2 seconds')); // executes later
sleep(1000).then(() => console.log('1 second')); // executes earlier
}
test();
Here, despite the order of calls, the output will be "1 second" followed by "2 seconds" due to different timer durations and Event Loop operation.