0

I'm trying to make a simple text slide show in pure javascript. Below is my code so far :

let currentChangingText = 0;
function changeText() {
    if (currentChangingText == changingTextsLength) currentChangingText = 0;
    $changingTexts[currentChangingText].setAttribute("class", "changing-text changing-text-slide-in");

    setTimeout(function() {
        setTimeout(function() { // *
            $changingTexts[currentChangingText].classList.remove("changing-text-slide-in");
            $changingTexts[currentChangingText].classList.add("changing-text-slide-out");
        }, 1000);

        $changingTexts[currentChangingText].classList.add("changing-text-hide");
        ++currentChangingText;
        changeText();
    }, 2000);
}

It "worked" but I've noticed something weird. On the first iteration (when the page loaded), the code block I've marked with * doesn't run at all so the slide out effect will not apply. On the next iterations it works fine (the slide out effect apply). I can't figure out what causes it, any help would be appreciated (plus if you know a better way to do this, please tell me as well!). Thanks in advance.

https://jsfiddle.net/15u2kfr0/

Ariando Miller
  • 1,261
  • 3
  • 18
  • 40

1 Answers1

1

the first 2000ms nothing happens because you delay it.

setTimeout(function() { // this is delay to load+2000
   setTimeout(function() { //you effectively delay this to load+3000
      //part1
   }, 1000);
   //part2
}, 2000);

you need to either delay them separately

setTimeout(part1,1000)
setTimeout(part2,2000)

or nest them correctly

setTimeout({part1, setTimeout(part2,1000)},1000)
apple apple
  • 5,557
  • 1
  • 12
  • 31