When requesting a sequence of data asynchronously using
ajax the data is not returned at regular intervals, or necessarily in the order the requests were made. The following code uses
setInterval to update the page at regular intervals - creating a smooth page-update. The data is inserted into table cells according to
the order the data was received.
The setIntervals are not initiated until half the data has been received, and will be cleared when all data has been processed. (An
else clause could be added so that the setInterval is cleared if there is an error in retrieving the remaining data.)
asyncAjax.html
Code:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style type="text/css">
#theTable { outline: 1px solid gray; }
#theTable td {
width: 40px; height: 50px;
}
</style>
</head>
<body>
<h1>10 Asynchronous Ajax Requests</h1>
<p>Here come the 10 random numbers..</p>
<div id="theDiv">Wait..</div>
<table id="theTable" summary="the data">
<tr><td> </td><td> </td><td> </td><td> </td><td> </td>
<td> </td><td> </td><td> </td><td> </td><td> </td></tr>
</table>
<script type="text/javascript">
function fncTrim(str) {
return str.replace(/^\s+|\s+$/g,'');
}
function insertData(vals) {
this.tbl = this.tbl || document.getElementById('theTable');
tbl.rows[0].cells[vals.shift()].firstChild.data = vals.shift();
}
for (var i=0; i < 10; i++) {
var counter = 1, vals = [];
(function (req, items, func) {
var thisone = i;
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
vals.push(thisone, fncTrim(req.responseText) * 1);
if (++counter == Math.floor(items / 2)) {
// start displaying in the table
updating = setInterval(function () {
if (vals.length > 0) {
func(vals);
} else if (counter > items) {
clearInterval(updating);
}
}, 500);
}
}
};
req.open("GET", 'createRandomNumber.php?rnd=' + Math.random(), true);
req.send(null);
}) (new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP"), 10, insertData);
}
</script>
</body>
</html>
createRandomNumber.php
PHP Code:
<?php
sleep(1); // 1 second
echo rand(1, 100);
?>
I suspect that this is more instructional, and hopefully interesting

, than directly applicable. [This follows from a recent thread which triggered my interest.]