DjangoDev DjangoDev - 27 days ago 7
Javascript Question

using setinterval for image slideshow

I am a beginer to javascript.I am trying to create a simple image slideshow using javascript.But it doesnt work.I dont know why.Please help me out.Thanks

<script>
var image=document.getElementById("aaa");
var img_array=["images/Chrysanthemum.jpg","images/desert.jpg","images/koala.jpg","images/penguins.jpg","images/hydrangeas.jpg","images/lighthouse.jpg","images/jellyfish.jpg"];
var index=0;
function slide()
{
image.setAttribute("src",img_array[index]);
index++;
if(index>=img_array.length)
{
index=0;
}
}
setInterval("slide()",2000);
</script>
</head>
<body>
<img id="aaa" src="images/tulips.jpg" width="400" height="400" name="image" />
</body>

Answer Source

simple way:

window.onload = function() {
    var image=document.getElementById("aaa");
    var img_array=[...];
    var index=0;
    var interval = 2000;
    function slide() {
        image.src = img_array[index++%img_array.length];
    }

    setInterval(slide, interval);
}

better way:

change setInterval(slide,2000); to:

setTimeout(function() {
    slide();
    setTimeout(arguments.callee, interval)
}, interval);