Whoops! I had to correct it to cancel the
setInterval once all the requests have been processed. Last change, I promise
Code:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style type="text/css">
#theTable { outline: 1px solid gray; }
#theTable td {
width: 50px; 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">
<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">
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,'');
};
var insertData = function (index, value) {
insertData.tbl = insertData.tbl || document.getElementById('theTable');
insertData.tbl.rows[0].cells[index].firstChild.data = value;
}
var MultiAjax = function MultiAjax(obj) {
this.Page = obj.Page || false;
this.Pages = obj.Pages || false;
this.Limit = obj.Limit || 10;
this.StartAfter = obj.StartAfter || Math.floor(this.Limit % 2);
this.Success = obj.Success;
this.Failure = obj.Failure || this.Success;
this.Delays = obj.Delays || 500;
this.Results = [];
}
// instance methods
MultiAjax.prototype = {
Go: function () {
var i = 0, that = this;
while (i < this.Limit) {
(function (req) {
var thisOne = i++;
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
that.Results.push(thisOne, (req.responseText).trim() * 1);
if (thisOne == that.StartAfter) {
// start displaying in the table
updating = setInterval(function () {
this.currentOne = this.currentOne || 0;
this.currentOne++;
if (that.Results.length > 0) {
that.Success(that.Results.shift(), that.Results.shift());
} else if (this.currentOne >= that.Limit) {
clearInterval(updating);
}
}, that.Delays);
}
} else {
that.Failure(thisOne, "Err!" + req.status);
}
}
};
//if (thisOne % 4) {
// req.open("GET", that.Page + Math.random(), true);
//} else {
// req.open("GET", 'DoesNotExist.php?rnd=' + Math.random(), true);
//}
if (that.Page) {
req.open("GET", that.Page + Math.random(), true);
} else if (that.Pages.length > 0) {
req.open("GET", that.Pages[thisOne], true);
}
req.send(null);
}) (new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP"));
}
}
};
var thisRun = new MultiAjax({
//Page: 'createRandomNumber.php?rnd=',
Pages: ['createRandomNumber.php?rnd=1235', 'createRandomNumber.php?rnd=0012',
'createRandomNumber.php?rnd=5859', 'createRandomNumber.php?rnd=0024',
'createRandomNumber.php?rnd=2003', 'createRandomNumber.php?rnd=0087',
'createRandomNumber.php?rnd=2587', 'createRandomNumber.php?rnd=0159',
'createRandomNumber.php?rnd=1598', 'createRandomNumber.php?rnd=2335'],
StartAfter: 5,
Limit: 10,
Delays: 500,
Success: insertData
// Failure: insertData
});
thisRun.Go();
</script>
</body>
</html>
BTW The random numbers retrieved duplicate occasionally because the PHP random function uses the time of the request to generate the number.