0

What I've heard is that Javascript engines are required to adhere to the rule

"If there's nothing to do, check the queue. But only check the queue if there's nothing to do."

and "the queue" is a queue of callback functions for asynchronous tasks. These are tasks that do not depend on the synchronous tasks and so they can be executed in parallel if the machine supports that. Let's say I have

SyncFunction1();
AsyncFunction1();
SyncFunction2();
AsyncFunction2();

Then order of execution is

Run SyncFunction1
Run SyncFunction2
Run callbacks of AsyncFunction1 and AsyncFuntion2

and whether the callback for AsyncFunction1 or AsyncFunction2 runs first depends on which task finished first. Is that correct?

  • Javascript is always executed in single thread, but for example AJAX requests can be executed in separate threads and other javascript code can be executed in a meanwhile. When request finishes the callback is placed in the queue. – Andrey Sep 16 '15 at 16:23
  • You are pretty much right. You can learn more about how javascript works by learning more about the event loop. https://www.youtube.com/watch?v=8aGhZQkoFbQ – toskv Sep 16 '15 at 16:25
  • Probably useful to read this [How does JavaScript handle AJAX responses in the background?](http://stackoverflow.com/questions/7575589/how-does-javascript-handle-ajax-responses-in-the-background/7575649#7575649) and the various other references in that answer. The JS event queue is explained there. – jfriend00 Sep 16 '15 at 16:25

0 Answers0