1

I am making a simple JS program and am having some trouble. You can view it here

http://codepen.io/TheAndersMan/pen/mOGVEy?editors=0010

Enter in your name and press enter, it will animate your name, but the letters disappear after the animation, which is understandable. what I don't understand is why my setTimeout isn't working and making them re-appear.

So here is the basic problem:

    var timeOut = (a / 2 + 1) * 1000;
          document.querySelector(".spanWrap").style.width = char.length * 60 + "px";
                  setTimeout(function() {
            thang.style.opacity = "1"
            thang.style.marginTop = "0";
    }, timeOut);

So hopefully that is all the info you will need, if not reference my pen, this is all in a for loop and if you see undefined variables here, they are defined in my pen.

So if someone can tell me what I did wrong that would be great.

Thanks in advance!

TheAndersMan
  • 376
  • 3
  • 14

2 Answers2

1

You have the infamous closure bug.

I noticed that you are transpiring using Babel. Using let instead of var for your variables local to your loop should fix the issue. Notice that in your broken CodePen, the last letter stays while the rest disappear. That is because your thang is always equal to the last letter by the time the timeout handlers execute (the loop has concluded long before).

See http://codepen.io/anon/pen/ObaVyb.

Also, a better idea might be to take a look at animation-fill-mode: forwards, which allows you to retain styles after animations have been run.

Finally, for those of you not using ES6, this code will allow you to achieve the same functionality without creating another wrapper function. (Essentially, setTimeout allows you to pass arguments to your callback when you register each handler.)

setTimeout(function (thang) {
    thang.style.opacity = "1"
    thang.style.marginTop = "0";
  }, timeOut, thang);
Community
  • 1
  • 1
gyre
  • 16,369
  • 3
  • 37
  • 47
0

The problem is, that you have several timeouts in for loop, that needs references to thang variables, but when your timeouts will be executed thang variable will be equal to the last thang in the cycle, so all the timeout would have the same reference. Hope it's clear.

So, to fix that, you need to bind your timeouts with thangs variables, one by one.

For example, you can do it with closures:

(function(thang) {setTimeout(function() {
    thang.style.opacity = "1"
    thang.style.marginTop = "0";
  }, timeOut);})(thang)
Telman
  • 1,444
  • 1
  • 9
  • 12