0

I'm trying to create an image rotator that displays certain images at certain times, but also rotates at other times in the day.

When I first created it, I just had it rotate every three seconds. That worked fine. But once I added the code to make a different image show up at different times, it quit working all together. Part of the problem is I'm confused about where I should put the setInterval and clearInterval. Anyway, here;s the code.

     <img id="mainImage" src="/arts/rotatorpics/artzone.jpg" />

JS:

    var myImage = document.getElementById("mainImage");
    var imageArray = ["arts/rotatorpics/artzone.jpg",
         "arts/rotatorpics/bach.jpg",
         "arts/rotatorpics/burns.jpg"];
    var imageIndex = 0;
    var changeImage = function() {
        mainImage.setAttribute("src", imageArray[imageIndex]);
        imageIndex++;
        if (imageIndex >= imageArray.length) {
            imageIndex = 0;
        }

    }

    var newDay = new Date(); //create a new date object
    var dayNight = newDay.getHours(); //gets the time of day in hours

    function displayImages() {
        if (dayNight >= 10 && dayNight <= 12) {
            mainImage.setAttribute("src", imageArray[1]);
        } else if (dayNight >= 17 && dayNight <= 19) {
            mainImage.setAttribute("src", imageArray[2]);
        } else {
            var intervalHandle = setInterval(changeImage, 3000);
        }
        myImage.onclick = function() {
            clearInterval(intervalHandle);
        };
    }​
adeneo
  • 312,895
  • 29
  • 395
  • 388
deadendstreet
  • 111
  • 1
  • 9

1 Answers1

1

first of all, all your variables seem to be are global, please dont do that, use an anonymous function-wrapper which executes your code (immediately (read about IIFE here. this is not part of your problem, but just good and clean coding style.

(function() {
  // your code here
})();

then i think one of your problems is your displayImages-function, which you declare but never call!

just should call it at the end of your code (or just leave it out)

displayImages();

if you want your images not to be swapped between 10-12 and 17-19 your code should then work as expected. if the images should swap even at this times, you shouldnt put the setInterval into the last else (inside your displayImages-function

hereandnow78
  • 14,094
  • 8
  • 42
  • 48