bobby
bobby

Reputation: 11

infinite loop for a slideshow

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

Answers (1)

nnnnnn
nnnnnn

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:

  • fixed your if test so that it doesn't process one more image than you actually have
  • added a maxStep variable rather than hardcoding the maximum within the function (obviously this is optional)
  • added semicolons everywhere - no you don't need them (for the statements in this function_), but I prefer to include them
  • updated the comment about setTimeout() to remove the implication that it functions like setInterval()
  • updated the call to 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 execute

Upvotes: 1

Related Questions