Shep Shep - 4 months ago 15
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:

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);
<img src="image1.png" name="image" width=800 height=600>

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


any help is appreciated many thanks!


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:


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

timer = setTimeout(imageCycle, 1000);