0

I've been searching all day and I can't figure out how to fix it.

All I wanna do is iterate through a bunch of elements and do the following things to each of it:

  • Add a class
  • Wait 3s
  • Remove the class added
  • Go to the next element

I've tried many things and now I have this:

/* Avatars is an array of elements */
var i = 0
function testimonialCarousel(avatars){
    const avatarsLen = avatars.length
    avatars[i].classList.add("focused-avatar");
    i++;

    if (i > 0){
        avatars[i-1].classList.remove("focused-avatar");
    };

    if (i < avatarsLen) {    
        setTimeout(testimonialCarousel.bind({}, avatars), 3000);
    } else{
        i = 0;
    };
};

I know that there are many questions here already covering the delay of a single function, for example: How do I add a delay in a JavaScript loop?

This is not my case. I can achieve it, adding the class for each element with a 3s interval. What I'm not able to achieve is the "remove class" step.

Does anybody may help me?

tripleee
  • 175,061
  • 34
  • 275
  • 318
2-D
  • 89
  • 10
  • I rolled back your latest edit because your question should remain strictly a question; but I have voted to reopen and encourage you to post your answer as an actual answer (and eventually mark it as accepted) once this gets reopened. – tripleee Oct 09 '19 at 07:26

1 Answers1

0

Ok, I've found out how to handle it:

for (let i = 0; i <= avatarsLen; i++){
        setTimeout(function(){
            if (i > 0){
                avatars[i-1].classList.remove("focused-avatar");
            };

            if (i == avatarsLen) {
                return testimonialCarousel();
            };

            avatars[i].classList.add("focused-avatar");
            balloonMessage.style.opacity = 0;
            balloonName.style.opacity = 0;
            setTimeout(function(){
                balloonMessage.innerHTML = balloonContent[i].message;
                balloonName.innerHTML = "— " + balloonContent[i].name;
                balloonMessage.style.opacity = 1;
                balloonName.style.opacity = 1;
            }, 650)

        }, i*3000);  /* <--- The solution lays here. */
2-D
  • 89
  • 10