Jump to content

setTimeout Method with for loops ?!?!!


skaterdav85

Recommended Posts

so this is my code, and i want to loop through an array so different images are displayed from the array, but when i run this code, it goes straight to the last image. Anyone know how to fix this?<script language="javascript">function swapImage(){ for(i=1; i<17; i++) { setTimeout("document.getElementById('picture').src = pic["+ i +"]",800) }}</script><body><input type="submit" name="play" id="play" value="Play" onclick="swapImage()" /> | <img src="abbey_large.jpg" id="picture" alt="cal student housing" width="432" height="324" /></body>

Link to comment
Share on other sites

Because you set the timeouts for all images at once, so every image is displayed almost instantaneously, and the last one is the one that ends up being shown. You could set the timeouts incrementally

function swapImage() {	for(i = 0; i < pic.length; i++) {		setTimeout("document.getElementById('picture').src = pic["+ i +"]",800 * (i + 1))	}}

Link to comment
Share on other sites

It is because you are actually setting 17 functions to run 800 milliseconds after the program runs through the loop. In other words, they all happen at once. If you want to run the setTimeout() as soon as the previous one has been finished, you could to use recursive functions.

Link to comment
Share on other sites

You'll have to set them to a variable, maybe even an array.Something like this:

timers = new Array();function swapImage() {  for(i = 0; i < pic.length; i++) {	timers[i] = setTimeout("document.getElementById('picture').src = pic["+ i +"]",800 * (i + 1))  }}

Then you can use clearInterval to stop the timeout. For example:

clearTimeout(timers[3]);

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...