Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop a series of image in javascript

i want to loop a series of images in javascript. below is the code i have so far

<html>
<head>
</head>

<body>
<img src="images/image1.jpg" alt="rotating image" width="600" height="500" id="rotator">

<script type="text/javascript">
(function() {
var rotator = document.getElementById('rotator');  // change to match image ID
//var imageDir = 'images/';                          // change to match images folder
var delayInSeconds = 1;                            // set number of seconds delay
// list image names
var images = ['1.jpg','2.jpg', '3.jpg', '4.jpg'];

// don't change below this line
var num = 0;
var changeImage = function() {
    var len = images.length;
    rotator.src = images[num++];
    if (num == len) {
        num = 0;
    }
};
setInterval(changeImage, delayInSeconds * 50);
})();
</script>
</body>
</html>

It can only display the image i have declared in the "var image". if i have 10000 image , how to do that . I have tried using a 'for' loop but it failed .. any suggestions ?? thanks in advance

==============================================================

update version that Joseph recommend :

<html>
<head>
</head>

<body>
<img src="images/1.jpg" alt="rotating image" width="600" height="500" id="rotator">

<script type="text/javascript">
(function() {
var rotator = document.getElementById('rotator'), //get the element
   var delayInSeconds = 1,                           //delay in seconds
   var num = 0,                                      //start number
   var len = 9999;                                      //limit
setInterval(function(){                           //interval changer
    num = (num === len) ? 0 : num;                //reset if limit reached
    rotator.src = num + '.jpg';                     //change picture
    num++;                                        //increment counter
}, delayInSeconds * 1000);
}());
</script>
</body>
</html>
like image 635
Eric Avatar asked May 15 '12 06:05

Eric


1 Answers

Assuming that images have the same sequential filenames, this would be best when looping through a lot of them:

(function() {
    var rotator = document.getElementById('rotator'), //get the element
        dir = 'images/',                              //images folder
        delayInSeconds = 1,                           //delay in seconds
        num = 0,                                      //start number
        len = N;                                      //limit
    setInterval(function(){                           //interval changer
        rotator.src = dir + num+'.jpg';               //change picture
        num = (num === len) ? 0 : ++num;              //reset if last image reached
    }, delayInSeconds * 50);
}());
like image 106
Joseph Avatar answered Oct 18 '22 14:10

Joseph