Reputation: 263
I'm trying to show/hide sponsor logos on my site, show/hide one after the other endlessly. I think I'm kinda close, but after banging my head, I decided it was time for help. Here's my code:
var sponsors = ["prointec","pequigraf"];
for (var i = 0; i < sponsors.length; i++){
setTimeout($(document.getElementById(sponsors[i])).slideToggle("slow", "swing"), 1000);
setTimeout($(document.getElementById(sponsors[i])).slideToggle("slow", "swing"), 10000 * (i + 1));
}
Basically, it should show one AFTER the other (after 10 seconds), but instead, runs all at once. Any hints? Thanks in advance!
Upvotes: 3
Views: 250
Reputation: 28870
I'm posting this as an answer instead of a comment just to make sure I can do some proper code formatting.
rpamely's code looks like just what you need, but you can simplify it quite a bit. Just prefix your two sponsor IDs with '#' and you can remove all the document.getElementById()
calls:
var sponsors = [ "#prointec","#pequigraf" ];
var i = 0;
$(sponsors[0]).show();
$(sponsors[1]).hide();
var toggleSponsor = function() {
$(sponsors[i]).hide();
i = (i + 1) % sponsors.length;
$(sponsors[i]).show();
setTimeout(toggleSponsor, 10000);
};
setTimeout(toggleSponsor, 10000);
Upvotes: 2
Reputation: 148
You need to give the timeout a function reference. Also you should be nesting your timeouts. Try to think asynchronously when writing JavaScript.
I haven't tested this, but this is what I came up with. Also note that 10 seconds is 10,000 milliseconds, not 1000.
var sponsors = ["prointec","pequigraf"];
var i = 0;
$(document.getElementById(sponsors[0])).show();
$(document.getElementById(sponsors[1])).hide();
var toggleSponsor = function() {
$(document.getElementById(sponsors[i])).hide();
i = (i + 1) % sponsors.length;
$(document.getElementById(sponsors[i])).show();
setTimeout(toggleSponsor, 10000);
};
setTimeout(toggleSponsor, 10000);
Upvotes: 1