Reputation: 1190
So I want to make a slideshow of pictures switching every two seconds, and I have this code.
HTML:
<div class="fadeIn">
<img src="img/city.png" class="remimg" id="city">
<img src="img/shop.png" class="remimg" id="shop">
<img src="img/ice-cream-cone.png" class="remimg" id="icecream">
</div>
JavaScript:
$(function(){
$('.fadeIn img:gt(0)').hide();
setInterval(function(){
$('.fadeIn :first-child').fadeOut()
.next('img').fadeIn()
.end().appendTo('.fadeIn');},
2000);
});
How do I make it only iterate once?
Upvotes: 1
Views: 23
Reputation: 318172
It's probably easier to use a recursive function without appending the images, and then just stop when the last image is reached
$(function() {
var all = $('.fadeIn img'),
first = all.first(),
last = all.last();
all.not(first).hide();
(function fn(image) {
setTimeout(function() {
var f = image.fadeOut().next().fadeIn();
if ( f.get(0) !== last.get(0) ) fn(f);
}, 2000);
}(first));
});
Upvotes: 2
Reputation: 26150
You could set a counter, assign the interval to a variable, and then clear the interval.
Modify your javascript like so:
$(function(){
$('.fadeIn img:gt(0)').hide();
// assign this to a variable, since we're going to check it often
var total = $('.fadeIn img').length;
// initialize the counter
// You can adjust this number as desired.
// For example, set it to 0 if you want the show to end on the first slide
var count = 1;
// assign the interval to a variable so we can clear it
var slideInterval = setInterval(function() {
// if the current slide count is equal to or greater than the total slides, clear the interval
if (++count >= total) {
// stops the slideInterval (and therefore the slideshow)
clearInterval(slideInterval);
// You could do other things here if desired....
}
$('.fadeIn :first-child').fadeOut()
.next('img').fadeIn()
.end().appendTo('.fadeIn');},
2000);
});
Upvotes: 1