Here is the fiddle https://jsfiddle.net/8p2jjr18/
The idea is to make a fading-in and fading-out rotation of testimonials in vanilla JS. The problem is that when the function runs for the fourth time in setTimeout, the first and subsequent elements in selection do not get the .fade
class. Instead, the .hidden
class gets applied right away (instead of waiting for the .fade
class to be applied and the animation on the class to end) and it messes up the whole picture.
I've tried to place break;
into the end of for
loop instead of the end of if
statement (see example below), but that breaks everything completely (just only one iteration happens), I have no idea why.
function rotateTestimonials() {
for (var i = 0; i < testimonials.length; i++) {
if (testimonials[i].className === "testimonial show") {
testimonials[i].className = "testimonial fade";
testimonials[i].addEventListener("animationend", function () {
testimonials[i].className = "testimonial hidden";
if (i + 1 !== testimonials.length) {
testimonials[i+1].className = "testimonial show";
}
else {
testimonials[0].className = "testimonial show";
}
}, false);
};
break;
};
}
I have two questions:
Why can't I place the
break
instruction into the end offor
loop?Why the function does not work as expected on the fourth and later iterations of
setTimeout
cycle?