0

With this article I create a simple javascript slideshow. but I can't understand why used from setTimeout on the last of codes. setTimeout just call one times the 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 Does not support the images class");

}
else {console.log("welcome to your slider")}


</script>
<body>
<img src = "1.png" name = "slide" id="slider" width="300" height="100" />
</body>
<script>
var step = 0
function slideit(){
//if browser does not support the 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

unbl0ck3r
  • 371
  • 4
  • 16

1 Answers1

1

Your code is looping as it should because the function is called again by the setTimeout at the end of the function.

function slideit(){
  // some code 

 //call function "slideit()" again in 2.5 seconds
 setTimeout("slideit()",2500)
}
slideit(); // call it initially

However it is not excellent programming. Several issues that are not good practice. Oh and by the way, document.images has been supported in all browsers since IE4

I would likely code it more like this without changing your 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 a look at this too

Execute the setInterval function without delay the first time

where the function and the code

slideit(); // first time or wait 2.5 secs
setInterval(slideit,2500); 

would be replaced by

setInterval(function slideit() {
  document.getElementById('slider').src = images[step];
  if (step>=2) step=0;
  else step++;
}(), 2500);
Community
  • 1
  • 1
mplungjan
  • 169,008
  • 28
  • 173
  • 236