sakarya
sakarya

Reputation: 393

Javascript Random Image by Time

I'm tring to show images randomly by the time. But I need a different thing.

var images = []
images[0] = "img/y0.gif";
images[1] = "img/y1.gif";
images[2] = "img/y2.gif";
images[3] = "img/y3.gif";
images[4] = "img/y4.gif";

images[5] = "img/1.jpg";
images[6] = "img/2.jpg";
images[7] = "img/3.jpg";

usedImages = [];
setInterval(function () {changeImage();},100);

var changeImage = function () {
    var index = Math.floor(Math.random() * (images.length)),
    thisImage = images[index];

    usedImages.push(thisImage);
    images.splice(index, 1);

    if (images.length < 1) {
        images = usedImages.splice(0, usedImages.length);
    }

    var imgStr = '<img src="' + thisImage + '" alt = "">';
    document.write(imgStr); 
    document.close();
}           

My codes work but if the image is a gif interval time must be 500, or if the image is image[2] time must be 500.

How can I do it?

Thanks..

Upvotes: 1

Views: 1234

Answers (2)

Abdelrahman M. Allam
Abdelrahman M. Allam

Reputation: 922

var changeImage = function () {
    var index = Math.floor(Math.random() * (images.length)),
    thisImage = images[index];
    var msec = 0;
    if(thisImage.split('.')[1] == 'gif'){
         msec = 500;            
    }else{
         msec = 300;            
    }
    setTimeout(changeImage, msec)
    usedImages.push(thisImage);
    images.splice(index, 1);

    if (images.length < 1) {
        images = usedImages.splice(0, usedImages.length);
    }

    var imgStr = '<img src="' + thisImage + '" alt = "">';
    document.write(imgStr); 
    document.close();

}  

Upvotes: 0

Andreas Louv
Andreas Louv

Reputation: 47099

You can use setTimeout(function, delay) inside changeImage and then initially call changeImage as well. This will make you able to change delay for each image:

var images = []
images[0] = "img/y0.gif";
// ...
images[7] = "img/3.jpg";

usedImages = [];

changeImage();

function changeImage() {
    var index = Math.floor(Math.random() * (images.length)),
    thisImage = images[index];

    // delay is 500 if image is .gif, and 100 if anything else
    var delay = thisImage.match(/\.gif$/) ? 500 : 100;
    setTimeout(changeImage, delay);

    usedImages.push(thisImage);
    images.splice(index, 1);

    if (images.length < 1) {
        images = usedImages.splice(0, usedImages.length);
    }

    var imgStr = '<img src="' + thisImage + '" alt = "">';
    document.write(imgStr); 
    document.close();
}

Upvotes: 1

Related Questions