Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Looping through and displaying items in an array

I have an array with 4 items that I would like to loop through and display infinitely. In this case, an H1 that flashes "One" then that fades out and flashes "Two", etc. Then starts over at the first element.

I'm not sure how to accomplish this.

I think I need to use setInterval somewhere in order to loop forever, but that also delays the start of the function to whatever the interval is. I'm also not sure how to get past the first item in the array. I think I need break or continue here, but neither really does the trick.

Check out this pen for what I have so far. Any help would be appreciated http://codepen.io/johndavidsimmons/pen/wzARpR

creating an infinite loop is a bad idea imo, I suggest you google it to understand why

2 Answers

In most programming languages, an infinite loop is a REALLY bad idea. Because of JavaScript's asynchronous nature, something like this is achievable, but I do not advise using an infinite loop!

Try instead creating a function that is called at an interval - check out this Stackoverflow question it should help answer your question: http://stackoverflow.com/questions/5835126/javascript-infinite-loop

It demonstrates how to write a function that will perform a list of instructions at a set interval.

I know not to create an infinite loop. I'm using setInterval in my pen and mention it in my post. I am having trouble stepping through the array at intervals

Hi John,

I think your pen changed from when I first looked at it.

Did you take a look at the accepted answer in the stackoverflow link that Jacob gave?

You can do it with 1 timer.