Very simple question: suppose I have the following js/jquery code
doSomething();
$.get(url, callback);
doSomethingElse();
I understand that right after the GET request is sent doSomethingElse() starts being executed. Now suppose that the server’s reply arrives while doSomethingElse() is executing. What happens?
- Does the callback run in a separate thread in parallel to doSomethingElse()?
- Does the execution of doSomethingElse() pause until the callback runs and returns?
- Does the callback only get called once doSomethingElse() has returned?
Thank you for any insight!
lara
No, JavaScript in web browsers is single-threaded, by design. That means that although the ajax call may start immediately (and be processed by another thread in the browser), your callback won’t happen until the JavaScript interpreter is next idle. Things to do get queued up waiting for the interpreter to become idle and process them.
Edit Answering your specific questions:
No, the callback will run in the same logical thread as
doSomethingElse. (It would be implementation-dependant whether that’s the same actual underlying OS thread, but you have no way of knowing and you don’t care; logically, it’s the same thread.)By default, the
getwill be asynchronous, so no.doSomethingElseinitiates the request, but then continues. (It’s possible to do a synchronous get via the underlying XmlHttpRequest mechanism, but it’s a very bad idea — tends to lock up the UI of the browser completely while the request is running, which is ugly — and I don’t know how you do it with jQuery.)With an asynchronous
get(the usual kind), you can be certain thatdoSomethingElsewill finish before the callback gets called, yes. This is because the JavaScript interpreter will only do one thing at a time, and it doesn’t switch to doing a new thing until it’s done with the current one. So althoughdoSomethingElsetriggers the get (and the get may be processed by other, non-JavaScript threads in parallel to JavaScript), your callback won’t happen until after the interpreter is done withdoSomethingElseand anything that called it.I wouldn’t be surprised if at some point we start getting multiple threads in browser-based JavaScript, but if and when we do, it’ll have to be explicit, since we all happily assume one thread for the moment.