0

if a promise creates a new micro task callback, and all micro tasks are resolved before processing the next macro task, why dont promises block the event loop?

Here is an answer the explains promises to be like an event notification system, clearly this is true because promises dont block, thats the point:

Do Javascript promises block the stack

But to be clear, if the callback is added to the micro queue, and that queue must be emptied to move on to the next macro task, why doesn't it block?

Craig
  • 1,648
  • 1
  • 20
  • 45

1 Answers1

2

It does block, for instance you may get blocked in a microtask checkpoint.

const block_loop = () => Promise.resolve().then( block_loop );

document.getElementById('btn').onclick = evt => {
  if( confirm("this will block this page") ) {
    block_loop();
  }
};
<button id="btn">block the event loop</button>
This frame will get blocked.

This example won't block the task from where it came from, but since microtasks queued from the microtask endpoint will get queued inside the same microtask queue that is being emptied, you'll actually end up in an endless loop and the event loop won't be able to process any future task.

Also microtask are tasks, and their processing itself will also block the event loop like any other task:

const block_loop = () => {
  const start = performance.now();
  while( performance.now() - start < 10000 ) {
    
  }
};
document.getElementById('btn').onclick = evt => {
  if( confirm("this will block this page for 10s") ) {
    Promise.resolve().then( block_loop );
  }
};
<button id="btn">block the event loop</button>
This frame will get blocked.
Kaiido
  • 123,334
  • 13
  • 219
  • 285