Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constantly loop a javascript array and display results to div?

I have a bunch of testimonials for my site which are currently on a page and am trying to get a div to display each 1 at an interval of 5 seconds, if the array reaches the last value it should start back to beginning of the array again.

Here is what I have so far...

var testimonial = new Array();
testimonial[1] = "Rugby";
testimonial[2] = "Baseball";
testimonial[3] = "Cricket";
var length = testimonial.length
var i = 1;
setInterval(function() {
    while (i <= length) {   
        $('#testimonials p').html(testimonial[i]);
        ++i;
        if (i == length) {
            i == 1;
        }
    }
}, 5000);

Any help would be great, thanks.

like image 266
Colonel Avatar asked Nov 24 '11 05:11

Colonel


People also ask

Can you loop through an array in JavaScript?

If we want to loop through an array, we can use the length property to specify that the loop should continue until we reach the last element of our array. In the loop above, we first initialized the index number so that it begins with 0 .

How do you make a for loop go through an array?

For Loop to Traverse Arrays. We can use iteration with a for loop to visit each element of an array. This is called traversing the array. Just start the index at 0 and loop while the index is less than the length of the array.

Which looping construct will iterate over the values of an array?

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.


1 Answers

Try

var testimonial = ['Rugby', 'Baseball', 'Cricket'];
var numTestimonials = testimonial.length;
var index = 0;

setInterval(function() {
    $('#testimonials p').text(testimonial[index]);        
    index = (index + 1) % numTestimonials;
}, 5000);

JavaScript arrays are 0-indexed and have handy array literal syntax. Using the modulus operator (%) is an idiomatic way of wrapping a counter back to 0 once it reaches a certain value.

like image 129
David Hu Avatar answered Sep 17 '22 16:09

David Hu