2011-09-16 131 views
0

我有一个示例的东西,我想放在一起,我需要清除超时完成后,按钮被单击,但只运行一次,我想清除超时,并能够再次点击它来通过这个过程。Javascript setTimeout clearTimeout问题

这里是低于

<!DOCTYPE html> 
<html> 
    <head> 
     <title>Animate Files</title> 
     <script type="text/javascript"> 
      var img0 = new Image(640, 960); 
      img0.src="img/Mouth-m.jpg"; 

      var img1 = new Image(640, 960); 
      img1.src="img/Mouth-o.jpg"; 

      var img2 = new Image(640, 960); 
      img2.src="img/Mouth-s.jpg"; 

      var img3 = new Image(640, 960); 
      img3.src="img/Mouth-e.jpg"; 

      var img4 = new Image(640, 960); 
      img4.src="img/Mouth-m.jpg"; 

      var i = 0; 
      var nbImg = 3; 

      function animate() { 
       document.images[0].src = eval("img" + i).src; 
       i++; 
       if(i == nbImg) i=4; 
       junk = setTimeout("animate();", 300); 
      } 
     </script> 
    </head> 
    <body> 
     <img src="img/Mouth-m.jpg" width="640" height="960"/> 
     <button type="button" onclick="animate()">One</button> 
    </body> 
</html> 

回答

0

列出的代码没有测试过这一点,但试一试:

<!DOCTYPE html> 
<html> 
<head> 
<title>Animate Files</title> 
<script type="text/javascript"> 
    var img0 = new Image(640, 960); 
    img0.src="img/Mouth-m.jpg"; 

    var img1 = new Image(640, 960); 
    img1.src="img/Mouth-o.jpg"; 

    var img2 = new Image(640, 960); 
    img2.src="img/Mouth-s.jpg"; 

    var img3 = new Image(640, 960); 
    img3.src="img/Mouth-e.jpg"; 

    var img4 = new Image(640, 960); 
    img4.src="img/Mouth-m.jpg"; 

    var hiatus; 

    function animate(i) { 
     clearTimeout(hiatus); 

     document.images[0].src = window['img' + i].src; 

     if(i === 4) { 
      return; 
     } 

     hiatus = setTimeout(function() { 
      animate(i + 1); 
     }, 300); 
    } 
</script> 
</head> 
<body> 
    <img src="img/Mouth-m.jpg" width="640" height="960"/> 
    <button type="button" onclick="animate(0)">One</button> 
</body> 
</html> 
+0

THX马歇尔我删除了我的形象之一,使其工作,我愿买电子健康尝试构建其他功能 –