How do I handle this jquery loop?
<p>I have an array of images that I want to loop through infinitely ie. 1, 2, 3, 1, 2, 3...</p>

<p>At first, I tried to do this using the following code:</p>

<pre><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);
</code></pre>

<p>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.</p>

<p>I figured an alternative way would be to set the value of an html field:</p>

<pre><code>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);

&lt;input type="hidden" id="currentItem" name="currentItem" value="0" /&gt;
</code></pre>

<p>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.</p>

<p>Am I missing something obvious here? I can't seem to figure out how to get this working.</p>

<p>If anyone has a more efficient method of achieving this I'd also be very grateful if you could share it :-)</p>

<p>Thanks</p>
