2

I know javascript runs on single thread. I also, know when we make an async ajax call using jquery, the code does not stop and continues execution serially. The response is handled by the callback. My question is how does the single thread does this? Does the thread handles the callback & stop the further code execution when we get the response back?

  • There's a very good answer to this [here](https://stackoverflow.com/a/7575649/712526), with lots of references included. – jpaugh Jul 17 '17 at 17:05

3 Answers3

7

No, it does not stop code execution.

The callback gets queued and when there is nothing else to execute, it will be run.

No two things happen at the same time, and scheduling is not pre-emptive.

So if you keep your single thread busy with things like infinite loops, the callback will never get a chance to run.

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • what do you exactly mean by 'nothing else to do' ?? And when exactly it gets a chance to run?? can u pls explain with an example? :)) – Supun Wijerathne Apr 06 '17 at 04:32
  • There is an event loop that (single-threadedly) runs all the scripts that need to be run. All callbacks are queued and will be run one after the other. If you put an infinite loop into one of those functions, that function will never finish and control does not return to the event loop. As a result, the queue no longer gets processed and the system hangs. – Thilo Apr 06 '17 at 06:37
1

The browser manages an event queue. When an event occurs, such as a response arriving from an Ajax call, a timer firing, or a mouse or touch event, the appropriate callback is being called on the main thread, when it is idle.

Adi Levin
  • 5,165
  • 1
  • 17
  • 26
1

This is not exsactly how it works as it depends on if you are using Node or a browser and which browser but it is a good mental model.

JavaScript is laying on top of another language like C which is multi threaded. When JavaScript runs a ajaxs request it will add the request to a queue and the language built to handle the network request will do it. When the request is done it changes the value in the queue. After every process cycle JavaScript will check this queue and run any callbacks linked to the completed tasks. So JavaScript does not do the process itself but just checks when they are done.

Michael Warner
  • 3,879
  • 3
  • 21
  • 45