Say you have a 'for' loop that runs an AJAX function for every item in an array and you want to view the progress of the function. Here's how I solved that problem:
<html>The key ingredient was 'setTimeout()', without it, the page would appear to hang while the 'for' loop executed.
<head>
<title>
</title>
<script type='text/javascript'>
function startAjax() {
// ... define yourArray[] for AJAX processing
for (var i=0;i<yourArray.length;i++) {
// loop through each item in the array and perform an AJAX process on it.
setTimeout('onReadyStateChangeFn("'+(Number(i)/Number(yourArray.length))*100+'%")',1000);
}
}
function onReadyStateChangeFn(perc) {
// ...
if (ajaxObj.readyState == 4 && ajax.status == 200) {
// ... your ajax-handling code here
document.getElementById('pbar_bar').style.width = perc;
// ... any additional code
}
}
</script>
</head>
<body>
<div id='pbar_frame' style='background:red;border:1px black solid;width=100%;height:1em;'>
<div id='pbar_bar' style='background:lime;width:0%;height:1em;'></div>
</div>
</body>
</html>
Enjoy!


0 comments:
Post a Comment