1分钟后停止setTimeout。环

时间:2015-08-21 10:36:03

标签: javascript jquery html

如何在1分钟后停止setTimeout。它继续因为loop.TIA

而继续
<script type="text/javascript">    
var image1 = new Image()
image1.src = "images/slide1.jpg"
var image2 = new Image()
image2.src = "images/slide2.jpg"
</script>
<body>
<p><img src="images/pentagg.jpg" width="500" height="300" name="slide" /></p>
<script type="text/javascript">
    var step=1;
    function slideit()
    {
        document.images.slide.src = eval("image"+step+".src");
        if(step<2)
            step++;
        else
            step=1;
        setTimeout("slideit()",2500);
    }
    slideit();
</script>

我尝试了很多东西,但我还是无法解决这个问题。我将不胜感激任何帮助。感谢

3 个答案:

答案 0 :(得分:0)

试试这个

setTimeout(function(){
  slideit();
},2500);

答案 1 :(得分:0)

您可以使用像

这样的计时器

var imgs = ['//placehold.it/500X300&text=1', '//placehold.it/500X300&text=2'],
  idx = 0,
  start = new Date();

function slideit() {
  document.images.slide.src = imgs[idx++];
  if (idx >= imgs.length) {
    idx = 0;
  }

  if (new Date().getTime() - start.getTime() > 10000) {
    clearTimeout(interval)
  }
}
var interval = setInterval(slideit, 2500);
slideit();
<p>
  <img src="images/pentagg.jpg" width="500" height="300" name="slide" />
</p>

答案 2 :(得分:0)

尝试命名setTimeout

var image1 = new Image();
image1.src = "images/slide1.jpg";
var image2 = new Image();
image2.src = "images/slide2.jpg";

var step = 1, timer; // declare here

function slideit() {
  
  if(timer){ // check if there is any timeout been set
     setTimeout(function(){
        clearTimeout(timer); // clear the timer here
     },5000); // change it to 60*1000 for 1 min == 60 sec == 60000 ms
  }
  
  document.images.slide.src = eval("image" + step + ".src");
  if (step < 2)
    step++;
  else
    step = 1;
  timer = setTimeout("slideit()", 500); // assign a timer here
}
slideit();
<p>
  <img src="images/pentagg.jpg" width="500" height="300" name="slide" />
</p>