-3

I currently need to keep looping through an array using javascript. The below is the one-way I can think of but 1-it doesn't work and 2- was wondering if their is a more optimal or compact way of achieving this?

var myArray=[1,2,3,4]

for (var i=0; i<myArray.length; i++)
{
     console.log(i + 'hi')
     if (i==3)
     {
        i=0;
     }

}
KingKongFrog
  • 13,946
  • 21
  • 75
  • 124
  • 3
    What exactly do you mean by "keep looping through an array"? Like, forever? Just use a `while (true)` loop. – Pointy Mar 11 '16 at 22:27
  • To get the value of the array at the index in your loop, do: myArray[i], not i, which is just the loop iterator. – devlin carnate Mar 11 '16 at 22:27
  • @Pointy Yes I can use while, but I want to keep iterating through myArray. What is the best way to keep track of the current element and then go back to element 0 – KingKongFrog Mar 11 '16 at 22:28
  • Even after you fix the reference to the array element with myArray[i], instead of i. You're going to have an infinite loop on your hands. Why do you want that? – Scott Marcus Mar 11 '16 at 22:29
  • At the end of the loop: `i = (i + 1) % myArray.length;` – Pointy Mar 11 '16 at 22:29
  • *" 1-it doesn't work"* Looks like it would work. What doesn't work? – Felix Kling Mar 11 '16 at 22:30
  • @ScottMarcus I'm trying to implement a loop that will display something every 10 seconds infintely. – KingKongFrog Mar 11 '16 at 22:30
  • @KingKongFrog well you're going to run into the problem of not being able to pause execution in JavaScript. – Pointy Mar 11 '16 at 22:31
  • 3
    *" I'm trying to implement a loop that will display something every 10 seconds infintely"* Then using a **synchronous** loop is the wrong approach in the first place. Why don't you explain what you are trying to do in your question? – Felix Kling Mar 11 '16 at 22:31
  • 1
    And you should mention this *"10 seconds"* part in your question. – trincot Mar 11 '16 at 22:32
  • To loop forever and restart whenever you reach the end of the array you can use: `for (var i = 0 ;; i = (i + 1) % array.length )`; of course, since Javascript is single-threaded you certainly don't want to loop forever, more likely you want to use `setInterval` or `setTimteout` to execute some code every 10 seconds. – Paul Mar 11 '16 at 22:32
  • if you want to display something every 10s infinitely, use `setInterval` – CrayonViolent Mar 11 '16 at 22:32
  • @KingKongFrog You will need to include setInterval() calls for the 10 second delay. – Scott Marcus Mar 11 '16 at 22:33
  • @FelixKling Sorry for the confusion. Let's say I want to change the class of an element every 10 seconds. The class names are in an array. That's theoretically what I'm trying to do. – KingKongFrog Mar 11 '16 at 22:34
  • 2
    Basically a duplicate of [Loop over array but with a time delay](http://stackoverflow.com/q/10965285/218196) – Felix Kling Mar 11 '16 at 22:34
  • 1
    Before I start typing my comment, I see *"Avoid answering questions in comments"*, but I seem to be the only one :) – trincot Mar 11 '16 at 22:34

5 Answers5

5

Based on the comments you want to do something every 10 seconds:

// IIFE to keep the variable i contained to a new scope
+function ( ) {

    var DURATION = 10;
    var i = 0;

    setInterval( function ( ) {

        // Do something every ten seconds 
        console.log( arr[i] );

        // Increment i (mod array.length)
        i = (i + 1) % array.length;

    }, DURATION*1000 );

}();
Paul
  • 139,544
  • 27
  • 275
  • 264
3

You could use the modulus operator

var i = 0;
// loop forever
while(true) {
    console.log(myArray[i] + 'hi');
    // i % 4 is the remainder when dividing i by 4
    // so this will cause i to be 0, 1, 2, 3, 0, 1, ...
    i = (i + 1) % myArray.length;
}
Justin Howard
  • 5,504
  • 1
  • 21
  • 48
-1

It would be nice to know more about what exactly you need, but this is one approach:

function loop(arr) {
    for (var i=0; i<arr.length; i++) {
        console.log('hi');
    }
    // OP wants a 10 second delay
    setTimeout(function () { loop(arr); }, 0);
}

Edit:

Since it says in the comments you want a 10 second delay we can change the 0 in set timeout to 10000. The plus side to using setTimeout as opposed to an infinite loop is that it allows other event driven things to occur in the script.

Robert Hickman
  • 997
  • 1
  • 11
  • 22
-1

Maybe this could work.

function foo() {
    var myArray = [1,2,3,4],
        i,
        len = myArray.length;
    for (i = 0; i < len; i += 1) {
       console.log(i + 'hi');
    }
}
while(true) {
    setTimeout(foo, 10000);
}
Emmanuel Lozoya
  • 128
  • 2
  • 10
  • 1
    This would "work" if your goal is to hang the browser :) – Pointy Mar 11 '16 at 22:47
  • The problem with this is that since setTimeout is in the loop, it will get put into javascript's event queue infinitely. If you put `setTimeout(foo, 10000)` inside of foo, it will do what I think you are expecting. – Robert Hickman Mar 11 '16 at 22:48
-2

Check out the following:

var myArray=[1,2,3,4]

for (var i=0; i<myArray.length; i++)
{
     console.log(myArray[i] + 'hi')

     if (i==3)
     {
        i=0;
     }

}

You were missing myArray[i]

Another problem is that this is an infinite loop because if i == 3 then it resets "i" back to zero causing your loop to never reach 4 ie. [1,2,3,4] ...just remove the if statement.

KpTheConstructor
  • 3,153
  • 1
  • 14
  • 22