Welcome to the Treehouse Community
Looking to learn something new?
Michael Mersiades12,920 Points
Why does the for loop in the code in this video never end?
But this for loop seems to last forever. Please help me to understand what is going on here.
The loop does not run infinitely, it only runs once for each
li element that is present when the page loads. But I think I can guess where your confusion is likely stemming from as it's a pretty common misunderstanding when watching this video.
Is your interpretation of the loop that it is responsible for making the
lis change case when hovered over? That is the impression a lot of people get, which does make it seem like the loop is running infinitely as the effect continues to work repeatedly.
In reality the
for loop is not the one responsible for the case changing, the
for loop is only responsible for attaching event listeners to the
li elements. The same effect could have been achieved without using any loop at all, but then you would have to have manually attached the event listeners to each element, which would have lead to a lot of redundant code.
The way an event listener works is that you essentially tell the browser "Hey when
x happens to this element run this code for me" where
x is the event you are listening for.
So in this video two events listeners are attached to the
lis one that runs when a mouse hovers over them and one that runs when a mouse stops hovering over them. The one responsible for monitoring the elements and running the code you wrote when one of those events occurs is the browser itself, not the loop.
If you are still confused or I misinterpreted what you where confused about, then just reply to this post and I'll do my best to clarify anything you want to know.
Moinul HaqFront End Web Development Techdegree Student 11,178 Points
Something wrong with your exit condition. Cross check it.