7

How are AJAX requests made asynchronous if Javascript is not multi-threaded?

Is the implementation browser specific?

0

1 Answer 1

8

The browser execution model is based on the concept of an "event loop". There's only one thread servicing events (slight oversimplification). When an event happens, handlers are called in sequence.

Ajax is just a mechanism that causes certain events. Setting up an HTTP request is synchronous, but just setting it up. The browser responds to the network communications representing the return data from the server by triggering events when that happens.

Modern browsers are somewhat more complicated in that each window may have its own process (or some other system-level "thread" construct, to be general). Also, the new "web worker" feature allows separate thread-like compartments to run concurrently.

Sign up to request clarification or add additional context in comments.

3 Comments

+1, perfect answer, clear and concise. Just 1 addition: In a way, JS implementations being single-threaded is indeed browser specific. But up until now, no implementation of JS (that I know of) supports multi-threading as such. In theory, it is possible, but the downsides are huge: the fact that JS is used by ppl who have no real understanding of the core concepts of (multi-threaded) development, coupled to the fact that many of those writing JS factually abuse the language. Honestly, Cthulu's rising will seem like a picnic compared to surfing to amateur made sites. No disrespect, though
Amateur programming is great, we all started out like that, but think what harm we could've done to our own machines if we got serious tools from day one? On the web, it's not just your machine you're wrecking... Basically, let JS be what it is: a great language, that starts of easy but has very neat constructs for those who are willing to look for them. There's so much to learn that threading can wait, 'till after learning about closures, lambda's, delegation, scopes, etc...
@EliasVanOotegem thanks! Well "Web Workers" can be implemented such that their code runs concurrently with code for the page (and other workers), but because the inter-thread communication model is so strictly message-based (like Erlang processes almost) it's relatively safe.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.