Undifined error after switching through images in Javascript

Advertisements

I am trying to create a website with one picture in the middle that changes after a given time. However after running through the loop once, no picture is shown for a short while and my console shows:

Shortly after, it switches through the images again. But having the image dissapear for a short while is a no go.

My Javascript looks like this:

var allPictures = new Array();
var index = 0;
allPictures[0] = "imgA.jpg";
allPictures[1] = "imgB.jpg";
allPictures[2] = "imgC.jpg";


addEventListener("load",() => {
    setInterval( function() {
        changeImage()
    }, 500);
});


function changeImage() {
    document.getElementById("galleryPicture").src = allPictures[index];
    if (index < allPictures.length) {
        index += 1;
    } else if (index >= allPictures.length) {
        index = 0;
    }
}

My HTML looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="main.css">
    <title>Website</title>
</head>
<body>

<script src="pictureSwapScript.js"></script>

<div class="galleryPicture">
<img id= "galleryPicture" src="imgA.jpg">
</div>
        
    
</body>
</html>

>Solution :

The problem is the condition used to increment index, it will get outside the boundaries of the array.

Replace it with

    if (index >= allPictures.length - 1) {
        index = 0;
    } else {
        index += 1;
    }

There are other minute improvements that can benefit your code, among which the most obvious to me is replacing:

    setInterval( function() {
        changeImage()
    }, 500);

with just

    setInterval(changeImage, 500);

Leave a ReplyCancel reply