Reputation: 3
I have a problem with a for loop in jQuery. I'm trying to build an ads section which will rotate dynamically to the last ad.
Unfortunately, jQuery gives me a static value for my incrementor.
Here is my code
function ads(){
var i = 0;
for(i=0; i<=3; i++){
$("#adBox").delay(5000).hide("slide", { direction: "up" }, 1000);
$("#adBox").delay(1000).show("slide", { direction: "right" }, 1000);
$("#adContent").load("adPage" +i+".php");
}
}
ads();
Upvotes: 0
Views: 156
Reputation: 26633
There are a couple of things going on here that might be relevant:
console.log("i: " + i);
inside the loop, you should see four lines written to the browser's JavaScript console when this code executes, e.g.:i: 0 i: 1 i: 2 i: 3
Each time the loop executes, the following things will happen, in this order:
"adPage" + i + ".php"
. Once the page is returned, it will be loaded into element #adContent. However, the .load() method returns immediately, without waiting for the page to be retrieved or loaded.The for loop probably completes all four iterations before the first call to .load() has even completed.
Finally, just a note about terminology: The for loop is built-in to JavaScript. It has nothing to do with jQuery, which is a JavaScript library.
I suspect that what you really want to happen is something like this:
function ads(i) {
if (i <= 3) {
$("#adBox").delay(5000).hide("slide", { direction: "up" }, 1000, function() {
$("#adBox").delay(1000).show("slide", { direction: "right" }, 1000, function() {
$("#adContent").load("adPage" + i +".php", function() {
ads(i + 1);
});
});
});
}
}
Those anonymous function arguments I'm passing to hide, show, and load are callback functions. They will be executed only after each function completes.
Upvotes: 1