skip to Main Content

In this code:

setTimeout(() => console.log('C'), 100); 
setTimeout(() => console.log('D'), 0);

someSynchronousTask() // Assume this takes ~500ms

This will log D -> C, but why?

Why wouldn’t it log C -> D? As setTimeout for C is pushed to event loop queue first and 500ms have passed which is > 100 ms. So, now both setTimeouts are ready to be executed. so, it should execute the `C` one as it was pushed to the queue earlier?

2

Answers


  1. It looks you is doing setTimeout functions first and then run a function that need 500ms.

    But please take a note the JavaScript is run from top to bottom.

    In my understanding and according to MDN web docs, I have found this solution:

    https://developer.mozilla.org/en-US/docs/Web/API/setTimeout says "setTimeout() is an asynchronous function"

    So the setTimeout and your task is running async.

    Login or Signup to reply.
  2. Javascript works with an execution stack and a parallel async queue to run its commands. Imagine you have a bunch of cards and you are ditributing them to be executed like in your code. The first one you’ll wait 100ms to be put in parallel queue, the second is immediately put in parallel queue, so the second card stands in front of the first in this queue, and then you start resolving the other cards in regular stack that takes 500ms. When the regular stack finally gets a free spot, you go back to look to the parallel queue and take the front card to be executed (during its execution, regular stack is busy again, so parallel queue is put to wait again, remaining the last card). Just when this execution is finished you’ll go back and take the last card from the queue (console.log(‘C’))

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search