I am a JS novice so go easy on me here. But I wrote a simple slideshow and it seems to be running very slow. The code below takes about 2-4 seconds to load locally on my own machine. Wondering what is causing the delay. Let me know, thanks!
function slideshow(){
$("#1").animate({top: "50px",}, 500).delay(2000);
$("#1").animate({top: "400px",}, 500);
$("#2").animate({top: "50px",}, 500).delay(2000);
$("#2").animate({top: "400px",}, 500);
$("#3").animate({top: "50px",}, 500).delay(2000);
$("#3").animate({top: "400px",}, 500);
$("#4").animate({top: "50px",}, 500).delay(2000);
$("#4").animate({top: "400px",}, 500);
$("#5").animate({top: "50px",}, 500).delay(2000);
$("#5").animate({top: "400px",}, 500);
slideshow();
}
Each ID represents a different image.
The big problem with your code, since none of the other answers seem to have talked about it yet, is that the last line of
slideshow()calls itself recursively, which will lead to a stack overflow. Don’t do this:Instead, if you want it to run repeatedly, use
setTimeout()to queue another execution of the function x milliseconds later:The way you had it, none of the functions ever actually finishes. With
setTimeout(), each invocation ofslideshow()does finish, and then a separate one runs after the specified delay. I’d make the delay big enough that the next invocation occurs after the current animations finish, otherwise you’ll be queuing up more and more animations faster than they run.UPDATE: jQuery maintains separate animation queues for each element, which means that the animations on your five elements will run simultaneously. Some of the other answers already provide ways of running the animations in sequence one at a time, but here is how I’d do it:
Working demo: http://jsfiddle.net/bARwb/
onload=attribute and as a convenient way of keeping the code out of the global scope (if you do it this way don’t forget to removeonload="slideShow()"from your body tag)..show()and.hide()calls (with a duration so that they join the animation queue) so that the img elements will havedisplay:nonein between animations because otherwise with yourposition:relativestyle you can’t see any but the first (but changing toposition:absolutewould prevent them getting cropped by their parent’soverflow:hidden)..hide()incrementsito refer to the next element’s index (but checks for when it goes past the last element) and then usessetTimeout()to queue the animation for that next element.