skip to Main Content
setTimeout(function(){
     console.log("hello async")
     }, 1000);
console.log("Hello sync");

setTimeout function console the hello async after delays of 1sec, after consoling Hello sync, so does it runs in background or in parallel.

3

Answers


  1. You can block the main thread and see that it runs in the same thread

    setTimeout(function() {
      console.log("hello async")
    }, 1000);
    const old = Date.now()
    // block thread fo 1.5s
    while (Date.now() < old + 1500) {}
    console.log("Hello sync");
    Login or Signup to reply.
  2. setTimeout effectively adds the function (and frame) to a queue to be run later when the main thread is not busy.

    Of course, it isn’t really a queue, as they are prioritized and ordered.

    Using console.log can further complicate things, because that is run the same way. What you output using console.log isn’t converted to a string and output until the main thread is not busy (behavior may vary on node.js or where console object is not the default).

    Login or Signup to reply.
  3. To be clear, setTimeout() is actually window.setTimeout() and window is not part of the Document Object Model or a native object in JavaScript.

    When you call setTimeout(), you are accessing a Web API and what happens next is that the browser will (asynchronously) begin a timer and when the time has elapsed, the callback function will be placed into the event queue. The next time the JavaScript runtime is idle, it will check the event queue and execute the next item in that queue.

    So, while the callback function is executed by the JavaScript runtime (and thus the single thread of that runtime), the timer itself is handled in a separate thread of the browser.

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