为什么在这个幻灯片上使用setTimeout?

时间:2015-07-27 12:01:57

标签: javascript slider

使用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>
&#13;
&#13;
&#13;

由于

1 个答案:

答案 0 :(得分:1)

您的代码正在循环,因为函数末尾的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);