Here is a simple snipped to do an Ajax request
var req = new XMLHttpRequest();
req.open('GET', 'http://www.mozilla.org/', true);
req.send(null); // First - send the request
// Then bind for the "result"
req.onreadystatechange = function (e) {
if (req.readyState == 4 && req.status == 200) {
// ...
}
};
What I am doing here:
- Sending the Ajax request.
- And then binding for the result callback.
If you think of this code as multithreaded – it is obvious that you can bind to onreadystatechage after the request has finished (due to scheduling) and it will never be called.
But in reactor-based code, this will work as expected all times since the reactor will not run until after all my code has finished running for that iteration.
Which is the case in browsers? Has this been documented somewhere?
Ignore that fact that an Ajax request is a slow thing and this might never happen in practice. I’m just giving it as an async example (think websocket if ajax is too slow for you).
JavaScript is not multithreaded in that sense. After you have said.send(null), you will finish executing your current block of code, which includes that onreadystatechange, and only then will events be fired. Your code will not be interrupted between those two sentences for an event firing – the event will be added to an event queue (buffered, if you will), and when there is time, the event will fire, calling all the handlers associated to it. It should call handlers that have been added between the creation of the XMLHttpRequest object and the firing of the event.
At least, this is my interpretation of the issue. For more information, visit Timing and synchronization in Javascript, at dev.opera.