Currently, I am facing a challenge while trying to create a basic automated slideshow from scratch. Though I have successfully built manual slideshows in the past, automating them is proving to be more complex. I started by experimenting with a for loop structure and the setInterval() method to replicate a looping effect:
$(function carousel() {
$('.slide:not(:first-child)').hide();
var slide1 = $('.slide:first-child');
var slide2 = $('.slide:nth-child(2)');
var slide3 = $('.slide:nth-child(3)');
var slide4 = $('.slide:last-child');
function moveSlide(currentSlide, nextSlide) {
setInterval(function () {
currentSlide.hide("slide", {direction: "left"}, 1000);
setTimeout(function () {
nextSlide.show("slide", {direction: "right"}, 1000);
}, 1000);
}, 1500);
}
var arr = [moveSlide(slide1, slide2), moveSlide(slide2, slide3), moveSlide(slide3, slide4)];
var i = 0;
setInterval(function () {
if (i < arr.length) {
arr[i] += 1;
console.log(i + "=>" + arr[i]);
} else {
return;
}
i++;
}, 1500);
});
You can view the code on Codepen.
Unfortunately, my attempts did not yield the desired outcome, as I anticipated. My understanding of JavaScript tells me that when using setInterval or setTimeout within a loop, the code will continue running without waiting for the loop to complete. Therefore, I seek suggestions for a workaround that doesn’t involve third-party libraries or plugins. Any insights closely aligned with my initial code would be greatly appreciated. Thank you!