Answer the question
In order to leave comments, you need to log in
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
let index = -1;
setInterval(() => {
index = (index + 1) % array.length;
console.log(array[index]);
}, 500);
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.
<div
@mouseenter="установитьИнтервал"
@mouseleave="сброситьИнтервал"
>
methods: {
установитьИнтервал() {
this.interval = setInterval(() => { ... }, 666);
},
сброситьИнтервал() {
clearInterval(this.interval);
},
},
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question