0

Javascript is said to be single-threaded. Also AJAX is said to be asynchronous.

Consider a scenario;

I have a button and on click of it, I make a AJAX call which takes 5-6 seconds. Now the UI would not be blocked and the user does some other action (say click on another button which is now executing some code, while the AJAX response has been returned). Now in this case, since the other code is being executed, when would the AJAX callback be executed? Would it have to wait OR can it be executed in a parallel thread ?

copenndthagen
  • 49,230
  • 102
  • 290
  • 442
  • You can run many parallel tasks in javascript. I don't know what's the technical background of it, but from my point of view, it's multithreaded. – Tomáš Zato Jan 13 '15 at 13:40
  • The AJAX callback will happen when your other code has finished executing. This is a consequence of the guarantee that any code that you write will not run concurrently with any other javascript code (web workers are the exception here). In general, Javascript is not well suited to long-running (synchronous) tasks in the browser. If you have to do any heavy-lifting, consider web workers which are javascript's best effort at providing thread-like behaviour. – spender Jan 13 '15 at 13:45
  • You might find [this question](http://stackoverflow.com/questions/14795145/how-the-single-threaded-non-blocking-io-model-works-in-node-js) enlightening. – spender Jan 13 '15 at 13:47
  • OP, did you not get sufficient answer? It's been a while, you know? – Tomáš Zato Mar 06 '15 at 12:18

2 Answers2

1

The events are queued, so when the Ajax call completes, the handler for that would be queued to run on the event loop. When the single thread is done with your button handler, it'll then process the next event in the queue. So - you would have to wait for the code kicked off by the button click to finish, unless of course the Ajax request completed before the user clicked on the button, in which case the button click handler had to wait. The best you can do is split up your algorithm so that it runs in discrete chunks, these can be dropped onto the queue using setTimeout, but that is quite tricky.

Woody
  • 7,578
  • 2
  • 21
  • 25
0

So I have searched a little about this topic in general. Contrary to what I have imagined, javascript is nothing like multi-threaded. Instead, it has a queue of operations it performs.

The direct answer then is: Depending on the very exact timing, the AJAX callback might have to wait before click event completes. It also might have to wait for any other code that was executed at "the same moment".

This explains while things like while(true) or alert() stop every script on the site.

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778