B
B
bozuriciyu2019-10-15 02:08:46
JavaScript
bozuriciyu, 2019-10-15 02:08:46

How to infinitely loop through an array with a delay?

There is an array with values ​​(strings). How to go through the entire array in a circle again, with a delay after each iteration? I did so, but what are the more elegant ways?

const array = ['one', 'two', 'three', 'four', 'five'];

function wait() {
  return new Promise(async (resolve, reject) => {
    setTimeout(() => {
      resolve();
    }, 500);
  });
}

async function loop() {
  for (const a of array) {
    console.log(a);
    await wait();
  }
  loop();
}

loop();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-10-15
@bozuriciyu

What setInterval did not suit?
let index = -1;
setInterval(() => {
  index = (index + 1) % array.length;
  console.log(array[index]);
}, 500);

UPD. Taken from the comments:
It seemed to be inconvenient to use in the View component. I need to show images from the array in a circle when hovering the mouse and stop when removing the mouse.

I don't see anything wrong :
<div
  @mouseenter="установитьИнтервал"
  @mouseleave="сброситьИнтервал"
>

methods: {
  установитьИнтервал() {
    this.interval = setInterval(() => { ... }, 666);
  },
  сброситьИнтервал() {
    clearInterval(this.interval);
  },
},

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question