4

Since Javascript engines in browsers have only 1 thread, when we create an XHR request using jquery, like so

$.ajax({
  url: "http://test.com/test.html",
  context: document.body
}).done(function() {
  $( this ).addClass( "done" );
});

on which thread does the HTTP request to the remote server occur, and what thread is it that notifies the main thread that the request is completed?

Arunabh Das
  • 13,212
  • 21
  • 86
  • 109
  • This might be useful: [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, pretty similar question to this one: [Do JS use Non blocking I/O at OS level to support AJAX?](http://stackoverflow.com/questions/9998433/do-js-use-non-blocking-i-o-at-os-level-to-support-ajax/9998602#9998602). – jfriend00 Jul 11 '15 at 03:42

2 Answers2

6

You have to remember the javascript is running within the browser -- the browser itself uses multiple threads and (especially in Chrome) multiple processes.

When you create an XHR request (it's an abstraction) the browser is going to open up a local TCP port itself within its permission levels, and run this task likely on its own thread.

This is why JS works so well for IO -- you can think of letting the browser open up a local tcp port and then communicating with the remote web server as similar to connecting and reading from a database with node.js.

The browser can open up multiple tcp connections, they can be shared underneath the hood, but then, when the responses return it can only process a response from one of these XHR requests (the abstraction talking to the browser) at a time within the JS event loop.

Although, workers (clustering and child.fork() in node) etc are also available in modern JS.

jpaugh
  • 6,634
  • 4
  • 38
  • 90
adamrights
  • 1,701
  • 1
  • 11
  • 27
0

First of all, when the browser load the JavaScript file, Then the $.ajax will be execute. There are two different way of XHR. first is set the async:false then the latter script will be executed after the XHR. Otherwise if we set the async:true. Then the XHR is send, but will be handle when the server response arrived.

albert hou
  • 66
  • 5