views:

61

answers:

2

Hello, I'm wondering if anyone can help me understand some asynchronous javascript concepts...

Say I make an asynch ajax call like so:

  xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange= myFoo;
  xmlhttp.open("GET",url,true);

Here is my callback function:

function myFoo()
{
if (xmlhttp.readyState==4)
  {
  if (xmlhttp.status==200)
    {
    // Success message
    }
  else
    {
    // some error message
    }
  }
}

Now, where and when does the execution path start again? Once I make the call to open(), does execution continue directly below the open() and another "thread" enters the asynch function once the ajax request has been completed?

Or, does the browser wait for the request to complete, make the Asynch call, and then execution continues right after the open?

Thanks!

+1  A: 

First, you are missing a xmlhttp.send call.

The browser doesnt wait for the request to complete to continue after the open. That is the entire idea behing a async call.

Rajat
Yeah I realize that... I guess it makes more sense to me in other languages because an asynchronous call is usually coming in as another thread... so I guess we have multithreaded javascript?
Polaris878
Nope, JavaScript is not multithreaded. The workers API is a latest addition that allows bending of rules but its fairly new.To wrap your head around what happens when the response comes back, read this link : http://www.javascriptkata.com/2007/06/12/ajax-javascript-and-threads-the-final-truth/
Rajat
I'm obviously not too familiar with asynch ways lol... thanks for the link
Polaris878
+1  A: 

Here is a pretty good explanation. http://stackoverflow.com/questions/598436/does-an-asynchronous-call-always-create-call-a-new-thread/617119#617119

Strelok
Wow yeah that helped a lot... thanks for the link
Polaris878