I think I understand your question. If you want to rotate through slides and restart when you get to the end here's what I'd do:
Firstly, create a function that we can pass an array of "slides". This function will have local variables that define the index of our current slide, and the index of the last slide (so we know when to restart).
We create a slide function that'll handle getting the elements, hiding/showing the next and previous elements, and incrementing (or resetting) our index.
var rotateSlides = function (slides, delay) {
// Start on the first slide in our list
var currentIndex = 0;
// Our final slide index
var lastIndex = slides.length - 1;
// Our main slide function
var slideFn = function () {
// The next slide, which we will be showing
var next = slides[currentIndex];
// declare previous, will be set later
var previous;
if (currentIndex === 0) {
// Set previous to the last slide in our list if we're current on index 0
previous = slides[lastIndex];
} else {
// Otherwise, set previous to currentIndex - 1
previous = slides[currentIndex - 1];
}
// Hide the previous slide
previous.style.display = "none";
// Show the next slide
next.style.display = "block";
if (currentIndex !== lastIndex) {
// Increment currentIndex if we aren't on our last slide
currentIndex += 1;
} else {
// Reset currentIndex if we ARE on our last slide
currentIndex = 0
}
};
// call our function right away to start it
slideFn();
// set an interval to call our function at the given speed
window.setInterval(slideFn, delay);
}
// Call our rotate function on a list of elemetns and
// pass a duration each slide should be visible for
rotateSlides([
document.getElementById('slide1'),
document.getElementById('slide2'),
document.getElementById('slide3')
], 1000);
<div id="slide1">Slide1</div>
<div id="slide2" style="display: none;">Slide2</div>
<div id="slide3" style="display: none;">Slide3</div>
If you want to slow it down so it takes 6 seconds, change 1000
to 2000
where we call rotateSlides
.
Reference:
https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval