0

i have image gallery ant i set up setinterval, now i want that it should be stopped after two or tree circle.

This is my html Code:

<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
}

and 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);
Giorgi
  • 83
  • 7

4 Answers4

2

Here's your answer: Stop setInterval call in JavaScript

Save the interval ID when you create it, keep track of the number of times your slides have rotated, and then cancel the interval.

Community
  • 1
  • 1
Simon Deconde
  • 309
  • 1
  • 4
0

Use a counter variable to track the number of cycles & clear the timer based on that limit value.

JS Code:

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);
dreamweiver
  • 6,002
  • 2
  • 24
  • 39
0

You could use setTimeout instead.

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

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

Pankaj
  • 54
  • 5