user37
user37

Reputation: 67

Creating a looping iterated list in array

I currently have this as an array:

    const arr = Array.from({ length: 10 }, (_, i) => `1 (${i + 1}).jgp`);
    
    console.log(arr);

I would like this array to constantly loop in the order it is in so that the output would be:

1 (1).jgp,1 (2).jgp,1 (3).jgp,1 (4).jgp,1 (5).jgp,1 (6).jgp,1 (7).jgp,1 (8).jgp,1 (9).jgp,1 (10).jgp,1 (1).jgp,1 (2).jgp,1 (3).jgp,1 (4).jgp,1 (5).jgp,1 (6).jgp,1 (7).jgp and so on....

The purpose of this is, because I would like to use these images to form an animation in HTML5 canvas, so that it would appear as a looping animation:

const images = Array.from({ length: 41 }, (_, i) => `1 (${i + 1}).jpg`);

let intervalId = setInterval(function () {
  if (images.length === 0){
    clearInterval(IntervalId);
    return;
  }
  // this remove the first image from the array and return it
  let imageName = images.splice(0, 1); 
  sendChat(`/set image http://mywebsite/directory/${imageName}`)
}, 300)

Please note that sendChat(`/set image are pre-defined variables in my website. The concern is not with the animation, I need help on looping through the array.

All help is appreciated, thanks.

Upvotes: 2

Views: 48

Answers (2)

Ori Drori
Ori Drori

Reputation: 191976

You don't need an infinite array. You need to iterate the indexes in a cyclic way - whenever you get to the last index, you go back to the start.

Use window.requestAnimationFrame() to render a frame, and if the runFlag is true, request the next frame. Use the remainder operator to cycle the the index:

let runFlag = true;
const loopImages = (i = 0) => requestAnimationFrame(() => {
  console.log(`1 (${i + 1}).jgp`); // render the image
  
  runFlag && loopImages((i + 1) % 10); // next frame
});

loopImages();

setTimeout(() => runFlag = false, 1000); // demo of stopping the loop

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386560

You could use a closure over the counter and adjust with the reminder operator %.

function loop() {
    var i = 0;
    return function () {
        console.log(`1 (${++i}).jgp`);
        i %= 10;
    };
}

setInterval(loop(), 200);

Upvotes: 2

Related Questions