1

I've researched and tried every variation I can think of with this seemingly simple snippet but it errors out indicating that the element is undefined. I'm simply trying to set the height of all elements with the class of 'eyes'.

I can write it out longhand subbing 0 and 1 for 'k', and I can set the loop to k<1 also works, but not for k<2 and there are clearly two class elements. Could someone tell me what I'm doing wrong?

<html>
   <svg>
      <rect class="eyes" transform="rotate(6 352 241)" x="352" y="241" width="70" height="3" fill="#DDC093"/>
      <rect class="eyes" transform="rotate(-8 230 245)" x="230" y="245" width="70" height="3" fill="#DDC093"/>
   </svg>
   <script>
      allEyes = document.getElementsByClassName('eyes')

      function blink(eyeno) {
        for (var k = 0; k < allEyes.length; ++k) {
          x01 = setTimeout(function() {
            allEyes[k].setAttribute("height", 20)
          }, 200);
        }
      };
      blink('eyes');
   </script>
</html>
George
  • 6,630
  • 2
  • 29
  • 36
iamattamai
  • 21
  • 2
  • Your issue is the `setTimeout`, it's running after the loop is finished so `k` will be `2`, as arrays start at 0, `allEyes[2]` would be `undefined` – George Jan 14 '19 at 14:42
  • 2
    Possible duplicate of [setTimeout in for-loop does not print consecutive values](https://stackoverflow.com/questions/5226285/settimeout-in-for-loop-does-not-print-consecutive-values) Understandably you wouldn't of know to search for this, but this should fix your issue :) – George Jan 14 '19 at 14:44
  • Thank you SO much - I failed to realize that the setTimeout wasn't defined upon setup, but evaluated at run-time. For future travelers, simply changing 'var' to 'let' in the 'for' loop code solved the issue. – iamattamai Jan 14 '19 at 15:29

0 Answers0