Reputation: 1194
I'm working on a script to rotate/cycle through images in javascript while respecting a limit on the amount of times it cycles through the images. What I have is below:
<a id="imageurl"><img id="Rotating1" border="0"></img></a>
<script language="JavaScript">
var delay = 3000; //6000 = change to next image after 6 seconds
var cycles = 2;
var currentCycle = 0;
function RotateImages(Start, delay)
{
var a = new Array("frown.gif","grim.gif","smile.gif", "bomb.gif");
var c = new Array("url1", "url2", "url3", "url4");
var b = document.getElementById('Rotating1');
var d = document.getElementById('imageurl');
var totalCycles = cycles * a.length;
// alert ("currentCycle: " + currentCycle);
// alert ("totalCycles: " + totalCycles);
if (Start>=a.length)
Start=0;
b.src = a[Start];
d.href = c[Start];
if (currentCycle < totalCycles) {
window.setTimeout("RotateImages(" + (Start+1) + ")", delay);
currentCycle++;
}
}
RotateImages(0, delay);
</script>
The script acts like it's working when I uncomment the alert boxes. When I comment them out, the rotation seems to stop. Any ideas on what is really going on and how to fix it?
Thanks!
Upvotes: 0
Views: 279
Reputation: 4164
One fundamental issue to take into consideration is with setTimeout
. The first parameter can be a reference to a function, whether it be an actual reference or a string reference, but you cant pass parameters along with it.
To do what you want, you need to pass a anonymous function to setTimeout. Also, Riyono is right that you should also pass the delay
setTimeout(function(){ RotateImages(Start++, delay) }, delay);
As far as your alert issue, I don't know what to tell you. But I know that the above will correct some issues.
Upvotes: 1
Reputation: 1389
perhaps you would like to change this line:
window.setTimeout("RotateImages(" + (Start+1) + ")", delay);
into:
window.setTimeout("RotateImages(" + (Start+1) + ", " + delay + ")", delay);
so that the next time RotateImages is called, it will keep the delay.
Upvotes: 1