如何在setInterval()方法后设置“停止”?

时间:2016-02-25 06:31:56

标签: javascript html css

我有图片库蚂蚁我设置了setinterval,现在我希望它应该在两个或树圈之后停止。

这是我的HTML代码:

<div id="slider">
  <img src="http://imgsrc.hubblesite.org/hu/gallery/db/spacecraft/24/formats/24_web.jpg">
    <img src="http://imgsrc.hubblesite.org/hu/gallery/db/spacecraft/27/formats/27_web.jpg">
  <img src="http://imgsrc.hubblesite.org/hu/gallery/db/spacecraft/32/formats/32_web.jpg">
    <img src="http://imgsrc.hubblesite.org/hu/gallery/db/spacecraft/33/formats/33_web.jpg">

</div>

的CSS:

#slider {
  width: 400px;
  height: 300px;
  position: relative;
  overflow: hidden
}

#slider img {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  transition: 0.25s
}

和Javascript:

var pics;
var current = 0; // first next() moves to pics[0], the first image

window.addEventListener("load", function() {
  pics = document.querySelectorAll("#slider img");
});

setInterval(function() {
  var nextImage = (current + 1) % pics.length;
   pics[current].style.opacity = 0;
  pics[nextImage].style.opacity = 1;
  current = nextImage;
}, 3000);

4 个答案:

答案 0 :(得分:2)

以下是您的回答:Stop setInterval call in JavaScript

创建间隔ID时,记录幻灯片旋转的次数,然后取消间隔。

答案 1 :(得分:0)

使用counter变量来跟踪周期数和周期数。根据该限制值清除timer

JS代码:

var counter = 0;
var limit = 3 ;
var timer;   

timer =setInterval(function () {
              if(counter === 3){
                 clearInterval(timer);
                 return;
              }
              counter++;
              //do some stuff here after 1 second delay
            },1000);

答案 2 :(得分:0)

您可以使用setTimeout。

var pics;
var current = 0; // first next() moves to pics[0], the first image
var stop = 3; //define when you want to stop

window.addEventListener("load", function() {
     pics = document.querySelectorAll("#slider img");
});

function switchImage()
{
    var nextImage = (current + 1) % pics.length;
    pics[current].style.opacity = 0;
    pics[nextImage].style.opacity = 1;
    current = nextImage;

    stop--;
    if(stop != 0)
        setTimeout(switchImage,3000);
}

setTimeout(switchImage,3000);

答案 3 :(得分:0)

你可以这样做。

var refreshIntervalId  =  setInterval(function() {
var nextImage = (current + 1) % pics.length;
pics[current].style.opacity = 0;
pics[nextImage].style.opacity = 1;
current = nextImage;
}, 3000);

clearInterval(refreshIntervalId);