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
  • 1,391
  • 4
  • 24
  • 43
  • Maybe https://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery will lead you into right direction. – Reporter Jan 13 '20 at 14:22
  • 1
    what you mean by *iteration*? – apple apple Jan 13 '20 at 14:22
  • @appleapple well, after 2000ms the ```changeText()``` function will get called again. The code block I've marked with ```*``` doesn't run on the first function call (triggered by ```DOMContentLoaded``` event (I've tried ```load``` event as well, still the same) – Ariando Jan 13 '20 at 14:26
  • Does this run after the DOM is rendered? – Shomz Jan 13 '20 at 14:26
  • 1
    @Shomz yes, I've tried ```DOMContentLoaded``` and ```load``` events, still the same – Ariando Jan 13 '20 at 14:27
  • Can you replicate it here as a code snippet? – Shomz Jan 13 '20 at 14:31
  • @Shomz here is the fiddle https://jsfiddle.net/15u2kfr0/ I guess it's maybe because there is something wrong with the logic – Ariando Jan 13 '20 at 14:44

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
  • 10,292
  • 2
  • 16
  • 36