Reputation: 37
This is probably fairly simple task for someone more experienced with javascript. I'd like to have an array of images and then loop through them to display each one with a certain interval of time between each one.
I know I could use a plugin, but I'm trying to learn javascript so I want to avoid taking shortcuts(except of course the shortcut of asking for help on here!)
Thanks
Upvotes: 1
Views: 7230
Reputation: 2910
Another option is to use a closure for the counter. Counters are most elegantly implemented as closures.
// Wrapping the code in a self envoking function prevents polluting the global namespace.
(function() {
// The images array.
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
// The counter function using a closure.
var add = (function() {
// Setting the counter to the last image so it will start with the first image in the array.
var counter = images.length - 1;
return function() {
// When the last image is shown reset the counter else increment the counter.
if(counter === images.length - 1) {
counter = 0;
} else {
counter+=1;
}
return counter;
}
})();
// The function for changing the images.
setInterval(
function() {
console.log(images[add()]);
}
, 1000);
})();
Upvotes: 0
Reputation: 1115
var img;
for(length)
{
img[i]=new Image();
img[i].src="src";
}
//for storing image as a array
var count=0;
var timerid = setInterval(function()
{
//fade in image
count++;
if(count > length)clearInterval(timerId);
}, 1000);
Better option is add all the image to DOM on image.onload with a display:none tag and then use a loop to fade in the image one by one,
Upvotes: 1