user1342164 user1342164 - 1 month ago 10
Javascript Question

Image not changing

Hi I am trying to get an image to blink using the code below by changing the image. Is there something wrong with my "setTimeout"? TIA

var Test = new Array();
Test.length = 2;

for (var i = 0; i < Test.length; i++) {
Test[i] = new Image();
Test[i].src = "images/Image2" + (i+1) + ".png";
}

function ChangeImage() {
for (var i = 0; i < Test.length; i++) {
document.getElementById('Test_Image').src = Test[i].src;
}
setTimeout("ChangeImage()", 1000);
}

ChangeImage();

Answer

First.. you complicated yourself with the new Image() part. You could just use Test[i] = "images/Image2" + (i+1) + ".png";

And for your code, firstly you change the images really fast once every 1 second.

It should be something like this:

function ChangeImage() {
    for (var i = 0; i < Test.length; i++) {
       setTimeout(function(){document.getElementById('Test_Image').src = Test[i]; 
        }, (i+1) *1000);      
    }      

   if(play){
     setTimeout("ChangeImage()", Test.length * 1000);        
   }
}   

This will not halt the javascript code at any point.

After 1 sec it will put image21, after 2 seconds image21 and it will call itself again and it will start all over again;

I put the variable play so you could stop the animation if you wanted.