The following code I have implemented for a javascript slideshow appears to speed up after about 5 iterations, from once every 15 seconds to what appears to be about 1 second between transitions. Is there something wrong with how the jquery/javascript implements the setTimeout?
var images = new Array(
'https://via.placeholder.com/150/0000FF',
'https://via.placeholder.com/150/FF00FF',
'https://via.placeholder.com/150/00FFFF',
'https://via.placeholder.com/150/FFFF00',
'https://via.placeholder.com/150/FF0000',
'https://via.placeholder.com/150/00FF00',
'https://via.placeholder.com/150/0000FF',
);
var nextimage = 0;
$(document).ready(function() {
doSlideshow();
})
function doSlideshow() {
if ($('.slideshowimage').length != 0) {
$('.slideshowimage').fadeOut(500, function() {
slideshowFadeIn();
$(this).remove()
});
} else {
slideshowFadeIn();
}
}
function slideshowFadeIn() {
if ($('.slideshow').length) {
$('.slideshow').prepend($('<img class="slideshowimage" src="' + images[nextimage++] + '" style="display:none">').fadeIn(500, function() {
setTimeout(doSlideshow, 15000);
}));
}
if (nextimage >= images.length) {
nextimage = 0;
}
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="slideshow"> </div>
Thanks
Advertisement
Answer
Use setInterval instead. You are currently adding new setTimeouts for every loop
I changed the speed to not have to wait 15 seconds
I also shortened the code and after spending far too long trying to figure out why the blue image showed twice, I removed one of the TWO blue pictures
var images = new Array(
'https://via.placeholder.com/150/0000FF',
'https://via.placeholder.com/150/FF00FF',
'https://via.placeholder.com/150/00FFFF',
'https://via.placeholder.com/150/FFFF00',
'https://via.placeholder.com/150/FF0000',
'https://via.placeholder.com/150/00FF00',
);
var nextimage = 0;
$(function() {
slideshowFadeIn();
setInterval(doSlideshow, 1500)
})
function doSlideshow() {
$('.slideshowimage').fadeOut(500, function() {
$(this).remove();
slideshowFadeIn();
});
}
function slideshowFadeIn() {
nextimage = nextimage%images.length; // infinite
$('.slideshow')
.prepend($(`<img class="slideshowimage" src="${images[nextimage++]}" style="display:none">`)
.fadeIn(500))
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="slideshow"></div>