Saturday, July 26, 2008

Using multi-threaded javascript to simplify AJAX

Concurrent.Thread is a JavaScript library that provides a thread-like syntax similar to that found in Java and C#. e.g. create, stop, sleep, notify and yield methods. (Finally, a sleep function for JavaScript!) This allows you to program in a synchronous way, possibly simplifying code flow and readability compared to the usual callback style of JavaScript.

For example, a typical asynchronous XMLHttpRequest (AJAX) flow that looks something like this:


var req = new XMLHttpRequest();
req.open("GET", url, true);
req.onreadystatechange = callback1;
req.send(null);

function callback1() {
if (req.readyState == 4) {
if (req.status == 200) {
alert(req.responseText);
} else {
alert(req.statusText); // Error
}
}
}


could alternatively be implemented in a synchronous way like so:


<script type="text/javascript" src="Concurrent.Thread.js"></script>
<script type="text/x-script.multithreaded-js">
var req = Concurrent.Thread.Http.get(url, ["Accept", "*"]);
if (req.status == 200) {
alert(req.responseText);
} else {
alert(req.statusText);
}
</script>


The synchronous code appears more compact, which could help make large application more readable.

How does Concurrent.Thread implement multi-threading in single threaded browser JavaScript engines? By simulating threads with time slicing.

Any downsides to using Concurrent.Thread? I suspect it will be a little slower due to simulating threads. It is also a very large download at 500k! (gzip it!)

No comments: