How do I create a Javascript banner switches pictures at different times?

4.2k Views Asked by At

I have a banner that has 10 pictures in it. I know how to set a timeout so the pictures switches every certain amount of seconds but how could I set a timer to change the picture based on how long I want individule ones displayed for.

For example: I want picture1 displayed for 10 seconds, picture2 displayed for 3 seconds and picture3 displayed for 15 seconds.

This is my code so far: (Which changes the all images at equal intervals of 5 seconds.

Javascript:

        window.onload = rotate;        
         var thisAd = 0;        
         var adImages = new Array("Images1/Picture10","Images1/Picture1","Images1  /Picture2","Images1/Picture3","Images1/Picture4","Images1/Picture5","Images1/Picture6","Images1/Picture7","Images1/Picture8","Images1/Picture9");

function rotate(){              
          thisAd++;
          if(thisAd == adImages.lengh){
            thisAd = 0;
          }     
          document.getElementById("adBanner").src = adImages[thisAd];       
          setTimeout(rotate, 5 * 1000);
}
3

There are 3 best solutions below

0
On

As your timeing has no logic a general algorithm can not be created. So you have to do a switch / else if for each ad.
You will also have to reset the counter, thisAd, after one cycle.

var time;
if(thisAd>9)thisAd=0;
if(thisAd==0)time=10;
else if(thisAd==1)time=3;
else if(thisAd==2)time=15;
...
setTimeout(rotate, time * 1000);
0
On

Make a times array to match your images.:

var adTimes = new Array(1000,5000,2000.....)

Use the value in the timer

setTimeout(rotate, 5 * adTimes[thisAd]);
0
On

You could store your pictures into objects with two properties: one for the URL, the other for the delay, then use that.

var adImages = [
    {
        url:"img1.png",
        delay: 5
    },
    {
        url:"img2.png",
        delay: 3
    }
];

Then you can use those properties:

var image = adImages[thisAd];
document.getElementById("adBanner").src = image.url;
setTimeout(rotate, image.delay * 1000);