Since I have written Ajax and javascript don’t use thread, one of my reader (BK) told me that I was wrong. Here's the final truth.

What I said

If javascript runs some code that takes 5 seconds to execute and an ajax response arrives at 2 seconds, it will take 3 seconds before it will be executed (before the callback function is called).
Example. We have a f() function that is incredibly long to execute (5 seconds) because it has a lot of code.

  1. function f() is started
  2. f() makes an ajax call
  3. f() is still executing since 2 seconds
  4. the response from the server arrives at the third second
  5. f() is still in execution for 3 seconds
  6. the callback function for ajax is called

    What he said

    Briefly, say I have CallPage1, CallPage2 and DoSomething. Both CallPage are async.

CallPage1 called CallPage2 called DoSomething called CallPage1 Returned (DoSomething is now paused) DoSomething ended CallPage2 Returned The DoSomething() function is paused when the ajax response arrives. The callback for the ajax is called and only then, DoSomething() resumes its execution.

That didn't make sense to me. Javascript is really sequential and it would not do that kind of complex stuff. But, I had to be sure.

The test

I made a simple page to test it all.

  1. Loop from 0 to X (user defined). X should be a big number.
  2. The first loop, it makes an ajax request
  3. The loops will finish someday
  4. The callback for the ajax will be called someday

I didn't know what to expect : will the callback function be called before or after the loop?

The result

I ran the script a lot of times with a lot of numbers and it was always the same thing : the callback function waits for the loop to be over before it is executed. It means that the current function is not paused.

Now it's your turn

I want you to take a look at the script (complete php code) (I know it's poorly written, it's just a test) and tell me if I'm wrong or if I'm right.

Thanks to you all!

comments powered by Disqus