简体   繁体   English

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

[英]How to set up “stop” after setInterval() method?

i have image gallery ant i set up setinterval, now i want that it should be stopped after two or tree circle. 我有图像画廊蚂蚁,我设置了setinterval,现在我希望它在两个或树圈之后停止。

This is my html Code: 这是我的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: CSS:

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

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

and Javascript: 和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);

Here's your answer: Stop setInterval call in JavaScript 这是您的答案: 停止JavaScript中的setInterval调用

Save the interval ID when you create it, keep track of the number of times your slides have rotated, and then cancel the interval. 创建间隔ID时请保存它,跟踪幻灯片旋转的次数,然后取消间隔。

Use a counter variable to track the number of cycles & clear the timer based on that limit value. 使用counter变量跟踪周期数,并根据该限制值清除timer

JS Code: 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);

You could use setTimeout instead. 您可以改用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);

You can do like this. 你可以这样

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM