2

If the Microtask Queue has more priority than the Macrotask Queue, why the order of console logs is

  • scriptStart
  • scriptEnd
  • setTimeout
  • Response

instead of

  • scriptStart
  • scriptEnd
  • Response
  • setTimeout

given that for(let i=0;i<100000000;i++){ const start = Date.now(); } takes enough time to keep the main thread busy, until the response from fetch arrives?

Full Code

console.log("scriptStart")

setTimeout(() => {
  console.log("setTimeout");
}, 0);

fetch("https://jsonplaceholder.typicode.com/todos/1").then(() => {
  console.log('Response');
});

for (let i = 0; i < 100000000; i++) {
  const start = Date.now();
}
console.log("scriptEnd")
trincot
  • 317,000
  • 35
  • 244
  • 286
glafche
  • 101
  • 6
  • The microtask-queue doesn't have any priority system, queued microtasks will get executed as soon as the JS stack is empty, or at the next microtask checkpoint. But here the fetch.then microtask will only get queued in an other task. – Kaiido Oct 22 '21 at 11:53

2 Answers2

2

As you can see in Network tab of debugger, the request to server starts only when thread was released (for loop ended). So, while fetch is receiving data from server, setTimeout has time to be done.

  • 1
    And also, although Promise is in Microtask queue, the question also use external resource (which is API request) – Raz Luvaton Oct 22 '21 at 10:50
  • So what I don't understand is why does the browser wait for the thread to be released (for loop to end) to make the request? – glafche Nov 04 '21 at 18:29
-1

Because the interpreter is singlethreaded. It looks like you are mistaking tasks for threads. They are not. They are just a linked list of callbacks.

The interpreter works like this:

    START
      │
      ▼
    execute
    javascript
      │
      ▼
    Event loop
    ┌──────────┐
    │          │
    │          │
    │          ▼
    │        check if there's any  ─────────▶ handle event
    │        event completion                       │
    │          │                                    │
    │          ▼                                    │
    │        check if we need to execute  ◀─────────┘
    │        any javascript in ───────────────▶ execute
    │        the microtask list                javascript
    │          │                                    │
    │          ▼                                    │
    │        check if we need to execute  ◀─────────┘
    │        any javascript in ───────────────▶ execute
    │        the macrotask list                javascript
    │          │                                    │
    │          │                                    │
    └────◀─────┴─────────────────◀──────────────────┘

It's all loops. Nothing runs in parallel. So as long as you are executing javascript you are not entering the event loop.

Note: If you are using worker_threads or webworkers then that's a different story because they really spawn threads.

slebetman
  • 109,858
  • 19
  • 140
  • 171