Reputation: 11
This is my code but i would like an infinite loop. Please help and be gentle. Explain where to put the code in full as i dont know html. if you have a better code for me to use i would appreciate this but i found this on the web and it works except for infinite loop. this is a 2 image slidehow.
<script type="text/javascript">
<!--
var image1=new Image()
image1.src="/v/vspfiles/assets/images/home1.jpg"
var image2=new Image()
image2.src="/v/vspfiles/assets/images/home2.jpg"
//-->
</script>
<div style="text-align: left;"><br></div><div style="text-align: center;"><img src="http://xvrlm.lhcjd.servertrust.com/v/vspfiles/assets/images/home2.jpg" name="slide" width="610" height="78">
<script>
<!--
//variable that will increment through the images
var step=1
function slideit(){
//if browser does not support the image object, exit.
if (!document.images)
return
document.images.slide.src=eval("image"+step+".src")
if (step<3)
step++
else
step=1
//call function "slideit()" every 2.5 seconds
setTimeout("slideit()",2500)
}
slideit()
//-->
</script>
Upvotes: 1
Views: 2694
Reputation: 150010
If you only have two slides then you need to make sure your step
counter only goes through the values 1 and 2 - your existing code will go through the values 1, 2 and 3 (you did have a test that said if(step<3)
but it was executing after the value 3 had already been used). Otherwise you're pretty close. Maybe something like this:
var step=1,
maxStep = 2;
function slideit(){
//if browser does not support the image object, exit.
if (!document.images)
return;
document.images.slide.src=eval("image"+step+".src");
if (step<maxStep)
step++;
else
step = 1;
//call self again in 2.5 seconds
setTimeout(slideit,2500);
}
slideit();
The changes I've made are as follows:
if
test so that it doesn't process one more image than you actually havemaxStep
variable rather than hardcoding the maximum within the function (obviously this is optional)setTimeout()
to remove the implication that it functions like setInterval()
setTimeout()
to pass a reference to the function rather than a string - it works either way, but passing a function reference doesn't lose the scope (not that that matter here) and is faster to executeUpvotes: 1