Skip to content

Instantly share code, notes, and snippets.

@donthorp
Created December 8, 2009 15:48
Show Gist options
  • Save donthorp/251738 to your computer and use it in GitHub Desktop.
Save donthorp/251738 to your computer and use it in GitHub Desktop.
An example that shows how to process a list asynchronously
<script>
var items = [
{ id : 1, value : 'item 1' },
{ id : 2, value : 'item 2' },
{ id : 3, value : 'item 3' },
{ id : 4, value : 'item 4' },
{ id : 5, value : 'item 5' }
];
function log(m) {
try {
document.getElementById('log').innerHTML += m + "<br/>";
} catch (E) {
alert(E);
}
}
window.onload = function() {
function XHR () {
this.doOnload = function() {
this.responseText = items[0].value;
try {
this.onreadystatechange();
} catch (E) {
alert(E);
}
};
this.send = function() {
var me = this;
// Fake time taken to get results and async
log("Simulating download...");
setTimeout(function() { me.doOnload()}, 1000);
};
};
function getStuff() {
try {
log("GetStuff called");
var xhr = new XHR();
xhr.onreadystatechange = function() {
var s = "ID: " + items[0].id + " has value: " + xhr.responseText;
document.getElementById('status').innerHTML = s;
items.splice(0,1); // pop
if (items.length > 0) {
setTimeout(getStuff, 100);
} else {
log("All items processed");
}
};
xhr.send();
} catch (E) {
alert(E);
}
}
setTimeout(getStuff, 1000); // Kick off first.
};
</script>
<div id='status'>No Status</div>
<div id='log'></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment