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(); }
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")
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.