skaterdav85 Posted November 16, 2008 Share Posted November 16, 2008 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 More sharing options...
Synook Posted November 16, 2008 Share Posted November 16, 2008 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 More sharing options...
Ingolme Posted November 16, 2008 Share Posted November 16, 2008 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 More sharing options...
skaterdav85 Posted November 16, 2008 Author Share Posted November 16, 2008 ohh ok thank you! i understand now. Do you know how i could stop the setTimeout function? I added a stop button, but i cant seem to find a method to stop the function or setTimeout method. any ideas? Link to comment Share on other sites More sharing options...
Ingolme Posted November 16, 2008 Share Posted November 16, 2008 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 More sharing options...
Ahamad Posted November 17, 2008 Share Posted November 17, 2008 I also had this type of problem.http://w3schools.invisionzone.com/index.php?showtopic=22080 Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.