I've the below piece of code and want to understand how event loop, macro-task queue and micro-task queue come into picture.
I've recently started learning about the above concepts so let me me know if I understand things correctly.
Whenever
setTimeout(callback, time)
is called, the JS engine lets the WebAPI handle the execution ofsetTimeout
. The WebAPI executes the setTimeout by waiting fortime
interval and followed by immediately putting the callback function in to the macro-task queue. Could anyone tell what all does -setTimeout(callback, time).then(anotherCallback)
do in terms of pushingcallback
andanotherCallback
into the different queues?The code inside a Promise runs synchronously in nature but whenever that promise gets resolved, the callback function attached to it gets pushed to the
micro-task
queue. Themicrotask
queue has higher priority as compared to themacrotask
queue.
Coming to the below code:
Promise.resolve()
.then(() => {
setTimeout(() => alert("timeout"), 0);
})
.then(() => {
alert("promise");
});
Promise resolves immediately, and the callback should be put into microtask queue so,
setTimeout(() => alert("timeout"), 0);
is put into the microtask queue. The event loop should put the above setTimeout into the callback queue for execution whenever the call stack becomes empty. The JS engine sees that setTimeout is an asynchronous function so it gives it to the WebAPI which handles its execution. The WebAPI waits for 0 seconds and puts the alert("timeout")
callback into the macrotask queue. This alert("timeout")
callback should be picked and put into the callback queue and alert "timeout" message should be generated.
I didn't quite get when does the last .then
executes which alerts the "promise" message on screen? I'm pretty sure that it's due to the promise returned by the setTimeout
and unsure on when does it executes.