Shep Shep - 3 months ago 6
Javascript Question

Javascript if statements in displaying images

Hey i am currently trying to get a program running in javascript i want the program to display the 4 images one after each other with the single press of a button and then after the 4 images have cycled through i want them to stop cycling and i cant seem to do it this is my code i currently have:

<html>
<head>
<script>
var images = ["image1.png","image2.png","image3.png","image4.png"];
var imagenum = 0;
var timer;
function imageCycle()
{
if(++imagenum == 4)
imagenum = 0;


document.image.src = images[imagenum];
timer = setTimeout("imageCycle()",1000);
}
</script>
</head>
<body>
<img src="image1.png" name="image" width=800 height=600>

<form>
<input type="button" value="images" name="cycle images" onclick="imageCycle()">

</form>
</body>
</html>


any help is appreciated many thanks!

Answer

In your code you continue to schedule the function, that's why the images continue to rotate.

If you want to stop at the forth image displayed, you have to put the setTimeout line in an else statement.

if (++imagenum == 4) {
    imagenum = 0;
} else {
    document.image.src = images[imagenum];
    timer = setTimeout("imageCycle()",1000);
}

Another point, that other users notice and I just report here in my answer.

You use the string:

imageCycle()

as the first argument of setTimeout, insted you should use just the function name.

timer = setTimeout(imageCycle, 1000);