Switching from one image to another

1.4k Views Asked by At

I'm trying to figure out how to switch from one image to another after 500 ms. What I have currently keeps switching between images, but I want each image to display for 500 ms and to have the second image disappear after that 500 ms instead of having it loop. This is what I have right now:

<html>
<head>
<title>loop</title>
<script type = "text/javascript">

function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}

function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
document.getElementById("img").src = images[x];
}
function startTimer() {
setInterval(displayNextImage, 500);
}

var images = [], x = -1;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
</script>
</head>
</html>
<body onload = "startTimer()">
<img id="img" src="image1.jpg">
</body>
</html>

Can anyone help me fix this? Thank you!

1

There are 1 best solutions below

2
On BEST ANSWER

This should do what you want it to do:

<html>
<head>
<title>loop</title>
<script type = "text/javascript">

    var images = [];
    var x = 0;
    var $img = document.getElementById("img");

    images[0] = "image1.jpg";
    images[1] = "image2.jpg";

    function displayNextImage() {
        if (++x < images.length) {
            $img.src = images[x];
            setInterval(displayNextImage, 500);
        }
        else {
            $img.remove();
        }
    }

    function startTimer() {
        setInterval(displayNextImage, 500);
    }


</script>
</head>
</html>
<body onload = "startTimer()">
<img id="img" src="image1.jpg">
</body>
</html>