为什么要在此幻灯片上使用 setTimeout?

why use setTimeout on this slideshow?

this 文章中,我创建了一个简单的 javascript 幻灯片。但我不明白为什么在最后一段代码中使用 setTimeout。 setTimeout 只需调用一次函数。

<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>

谢谢

您的代码正在正常循环,因为该函数在函数末尾被 setTimeout 再次调用。

function slideit(){
  // some code 

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

然而,这不是优秀的编程。有几个问题不是很好的做法。哦,顺便说一句,自 IE4

以来,所有浏览器都支持 document.images

在不更改预加载器的情况下,我可能会更像这样编写代码:

<!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>

这个也请看看

Execute the setInterval function without delay the first time

其中函数和代码

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

将被替换为

setInterval(function slideit() {
  document.getElementById('slider').src = images[step];
  if (step>=2) step=0;
  else step++;
}(), 2500);