Mathieu Ferraris
Mathieu Ferraris

Reputation: 97

loop that continuously goes back and forth

I'm trying to have an infinite loop that goes back and forth through an array, the function that I have goes forward and I want it to go backward once i = array.length. here's my code:

    var myArray = ["banana", "apple", "peer", "grape"]

    var i = 0;
    
    (function loop() {
        console.log(myArray[i])
        if(i++ < myArray.length-1){
            setTimeout(loop, 1000);
        }
    })();

I'm missing the backward part because what I tried didn't work,

Any help will really be appreciated

Upvotes: 0

Views: 698

Answers (3)

Kyy13
Kyy13

Reputation: 315

Here is another way that counts up then down, etc.

var i = 0;
var maxIndex = 9;
var dir = 1;

while(true)
{
    if (i == maxIndex*dir) dir = !dir;

    doSomething(i);

    i += (dir<<1)-1;
}

Upvotes: 0

j08691
j08691

Reputation: 207901

Here's one way that reverses the array when it hits the length:

var myArray = ["banana", "apple", "pear", "grape"];
var i = 0;
(function loop() {
  if (i < (myArray.length - 1)) {
    console.log(myArray[i]);
    i++;
  } else {
    myArray.reverse();
    i = 0;
    console.log(myArray[i]);
    i = 1;
  }
  setTimeout(loop, 1000);
})();

Upvotes: 1

Tom
Tom

Reputation: 2611

This might be something you're looking for. I haven't run it in anything so there may be some errors, but it should give you a gist of what you're aiming for.

const myArray = ["banana", "apple", "peer", "grape"];
let index = 0;
let direction = 0;
const maxLoops = 50;
let loopCount = 0;

while (loopCount < maxLoops) {
    console.log(myArray[index]);
    if (direction === 0) {
        index++;
    } else {
        index--;
    }


    if (direction === 0 && index >= myArray.length - 1) {
        direction = 1;
    } else if (direction === 1 && index <= 0) {
        direction = 0;
    }

    loopCount++;
}

Upvotes: 0

Related Questions