I have an array of images that I want to loop through infinitely ie. 1, 2, 3, 1, 2, 3…
At first, I tried to do this using the following code:
var images = [
"/images/image1.jpg",
"/images/image2.jpg",
"/images/image3.jpg"
];
var obj = { currentValue: 0 };
var maxValue = 2;
//loop through the items
var infiniteLoop = setInterval(function() {
if(obj.currentValue == maxValue) {
obj.currentValue = 0;
}
// ... Code to fade in currentItem ...
obj.currentValue++;
}, 5000);
I’d read that this is correct method of passing in a variable by reference but for some reason, I’m never able to set the obj.currentValue back to 0 when all the images have been looped through.
I figured an alternative way would be to set the value of an html field:
var images = [
"/images/image1.jpg",
"/images/image2.jpg",
"/images/image3.jpg"
];
var maxValue = 2;
//loop through the items
var infiniteLoop = setInterval(function() {
if(parseInt($('#currentItem').val()) == maxValue) {
$('#currentItem]').val('0');
}
//... code to fade in currentItem ...
var tmp = parseInt($('#currentItem').val());
tmp++;
$('#currentItem').val(tmp);
}, 5000);
<input type="hidden" id="currentItem" name="currentItem" value="0" />
However I’m still having the same problem. For some reason, whenever I hit the end of the image list, I’m unable to set the value of the hidden field and my infinite loop never gets to restart.
Am I missing something obvious here? I can’t seem to figure out how to get this working.
If anyone has a more efficient method of achieving this I’d also be very grateful if you could share it 🙂
Thanks
So I rewrote your js a bit, with comments on how/why to do things
And here in jsFiddle:
http://jsfiddle.net/sg3s/RGQxY/5/
You’re using jquery to do things, that is fine, but you’ll have to pass jQuery to be able to use it inside that immediately invoked function that wrapper could look something like this:
(function ($, window) { /* code goes here */ }( jQuery, window ));.