javascript - why use setTimeout on this slideshow? -
with this article create simple javascript slideshow. can't understand why used settimeout on last of codes. settimeout call 1 times function .
<html> <script> var images = new array(); images[0] = new image().src = "1.png"; images[1] = new image().src = "2.png"; images[2] = new image().src = "3.png"; images[3] = new image().src = "4.jpg"; if (!document.images){ console.log("your browser not support images class"); } else {console.log("welcome slider")} </script> <body> <img src = "1.png" name = "slide" id="slider" width="300" height="100" /> </body> <script> var step = 0 function slideit(){ //if browser not support image object, exit. if (!document.images) { console.log("your browser doesn't support our site")} document.getelementbyid('slider').src = images[step] if (step<2) step++ else step=0 //call function "slideit()" every 2.5 seconds settimeout("slideit()",2500) } slideit() </script> </html>
thanks
your code looping should because function called again settimeout @ end of function.
function slideit(){ // code //call function "slideit()" again in 2.5 seconds settimeout("slideit()",2500) } slideit(); // call
however not excellent programming. several issues not practice. oh , way, document.images has been supported in browsers since ie4
i code more without changing preloader:
<!doctype html> <html> <script> var step=0,images=[]; images[0] = new image().src = "1.png"; images[1] = new image().src = "2.png"; images[2] = new image().src = "3.png"; images[3] = new image().src = "4.jpg"; function slideit(){ document.getelementbyid('slider').src = images[step]; if (step>=2) step=0; else step++; } window.onload=function() { slideit(); // first time or wait 2.5 secs setinterval(slideit,2500); } </script> <body> <img src="1.png" name="slide" id="slider" width="300" height="100" /> </body> </html>
please have @ too
execute setinterval function without delay first time
where function , code
slideit(); // first time or wait 2.5 secs setinterval(slideit,2500);
would replaced
setinterval(function slideit() { document.getelementbyid('slider').src = images[step]; if (step>=2) step=0; else step++; }(), 2500);
Comments
Post a Comment