Search code examples
javascriptasynchronousxmlhttprequestsettimeoutweb-worker

setTimeout vs WebWorker vs XMLHttpRequest


I need to understand these concepts more clearly as i'm not sure about them. Javascript is single-threaded, so far, so good.

  1. From my understanding setTimeout is just delaying the execution of the code from the main thread but the callback it's still executed on the main thread when the call stack is empty. Is this correct? Same would be true for Promises and Event Handlers.

    setTimeout(() => {
    console.log('this line of code is executed on the main thread');
    }, 5000);
    
  2. For asynchronous requests using XMLHttpRequest the actual request is sent to a separate API implemented by the browser that runs it on a separate thread, thus, it is truly asynchronous. Is this correct?

  3. WebWorkers would be another API implemented by the browser that also runs the code from the given script in a background thread. Is this correct?

I would greatly appreciate an answer to this question!


Solution

  • You're generally correct in all three points.

    1. Set timeout and any other asynchronous functions are queued to be executed when the prerequisite completes. So, when the call stack is empty and there's a job to do, JS picks the next queued function and executes it. This is handled by what is called javascript event queue.
    2. There isn't much practical difference from setTimeout. Both functions will queue your callback once complete, code responsible for that is implementation defined, so browsers can chose how they do it as far as multithreading is concerned.
    3. Yes, worker runs in another thread and has it's own event loop. If it sends message to main thread, callback for that message is queued to run in main thread with that message and vice versa. Note that as far as I know, web browsers are not obligated to have exactly one thread per one worker, but that's something that shouldn't affect you in any way.