function updateItem(str)
{
var stocks =new Array("GOOG","MSFT","AAP","JDAS","G");
for(var i=0; i<stocks.length;i++)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="php/updateCart.php";
url=url+"?q="+stocks[i];
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange= function(){
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById(stocks[i])
.innerHTML=xmlHttp.responseText;
}
}
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
}
function startOff()
{
if(interval != -1)
{
clearInterval(interval);
}
interval = setInterval(function() {updateItem()}, 1000);
}
I’m trying to update multiple divisions in a form in a interval the problem is the for loop is going to fast for the request to finish. I didn’t realize this til I made a bunch of alerts and notice when I push enter slowly…I know you can do it maybe with a setTimeout but the syntax I just can’t seem to get down right. Since the I don’t have a name to the function to check the readystate can someone give me a hint on the syntax. Or if there a more simple way of doing it…I would appreciate it.
Edit: I got things a bit mixed up and thought javascript had block scope. That’s what happens when you try to solve problem in that many languages I suppose. The problem is still sort of the same, but the solution isn’t. I’m still not going to solve this using the timeout you used (or starting the next request when the previous one is done), as I don’t think that’s the correct way to go. Instead, I am going to solve the underlying problem which the timeout technique only tries to work its way around.
The problem isn’t so much in that the for loop is “too fast”. The problem is that the variables you use in your callback function have a scope that is larger than the for loop body. This means that you set the same variables to different values each time. As such, the variables will have the final value when the callback function is finally called.
One way to fix this would be to move the creation of the request to a new function like this:
That is probably the easier way to understand, but personally I like the way below more. It basically does the same thing, but using a little Javascript trickery with an anonymous function we call immediately, we no longer need a separate function like that, but can instead handle this inline: