I am trying to create a simple slideshow consisting of 3 rotating images that will start over as soon as the last has displayed, timed 5000ms apart.
<div id="slideshow"> </div>
<script type="text/javascript">
var imageArray = ['Image1','Image2','Image3'];
var currentIndex = 0;
nextPic = function(currentIndex,slideshow) {
var theHTML = '<img src="http://www.domain.com/Pics/Test-' + imageArray[currentIndex] + '.jpg">';
document.getElementById("slideshow").innerHTML = theHTML;
if (currentIndex < imageArray.length) {
currentIndex = currentIndex + 1;
}
else {
currentIndex = 0;
}
setTimeout("nextPic(" + currentIndex + ")", 5000);
}
nextPic(currentIndex, "slideshow");
</script>
Every variation of Javascript code I have found has produced the same result: after the last image (Test-Image3.jpg), the JS attempts to display an undefined image ("Test-undefined.jpg") before resetting back to the first one. It works perfectly fine other than that and it's quite maddening.
You need to take into account the fact that you're adding one after checking against the length of the array:
if (currentIndex < imageArray.length - 1) {
currentIndex = currentIndex + 1;
}
else {
currentIndex = 0;
}
or
currentIndex += 1;
if (currentIndex >= imageArray.length)
currentIndex = 0;
You really don't need to pass the parameter at all, however, because the function can just use the global variable. (It'd be better not to have one, but since you do, well, you might as well use it.)