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?
JavaScript
x
36
36
1
var images = new Array(
2
'https://via.placeholder.com/150/0000FF',
3
'https://via.placeholder.com/150/FF00FF',
4
'https://via.placeholder.com/150/00FFFF',
5
'https://via.placeholder.com/150/FFFF00',
6
'https://via.placeholder.com/150/FF0000',
7
'https://via.placeholder.com/150/00FF00',
8
'https://via.placeholder.com/150/0000FF',
9
);
10
var nextimage = 0;
11
12
$(document).ready(function() {
13
doSlideshow();
14
})
15
16
function doSlideshow() {
17
if ($('.slideshowimage').length != 0) {
18
$('.slideshowimage').fadeOut(500, function() {
19
slideshowFadeIn();
20
$(this).remove()
21
});
22
} else {
23
slideshowFadeIn();
24
}
25
}
26
27
function slideshowFadeIn() {
28
if ($('.slideshow').length) {
29
$('.slideshow').prepend($('<img class="slideshowimage" src="' + images[nextimage++] + '" style="display:none">').fadeIn(500, function() {
30
setTimeout(doSlideshow, 15000);
31
}));
32
}
33
if (nextimage >= images.length) {
34
nextimage = 0;
35
}
36
}
JavaScript
1
3
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<div class="slideshow">
3
</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
JavaScript
1
28
28
1
var images = new Array(
2
'https://via.placeholder.com/150/0000FF',
3
'https://via.placeholder.com/150/FF00FF',
4
'https://via.placeholder.com/150/00FFFF',
5
'https://via.placeholder.com/150/FFFF00',
6
'https://via.placeholder.com/150/FF0000',
7
'https://via.placeholder.com/150/00FF00',
8
);
9
var nextimage = 0;
10
11
$(function() {
12
slideshowFadeIn();
13
setInterval(doSlideshow, 1500)
14
})
15
16
function doSlideshow() {
17
$('.slideshowimage').fadeOut(500, function() {
18
$(this).remove();
19
slideshowFadeIn();
20
});
21
}
22
23
function slideshowFadeIn() {
24
nextimage = nextimage%images.length; // infinite
25
$('.slideshow')
26
.prepend($(`<img class="slideshowimage" src="${images[nextimage++]}" style="display:none">`)
27
.fadeIn(500))
28
}
JavaScript
1
2
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<div class="slideshow"></div>