How to return one value in an array decreasing by one in a for loop

Viewed 53

I would like to return values in an array starting from 5 to 0 in a for loop every 5 seconds. Here is my code

function x() {
let array = [1,2,3,4,5,6,7,8]
let value = array.slice(0,5)
for(i = 5-1; i>=0; i--){
    console.log(value[i])

}
setTimeout(x, 5000)
}

x()

My Problem is, this returns 5,4,3,2,1 every 5 seconds. I would like it to return 5(wait 5sec) 4(wait 5sec) 3(wait 5sec) etc...

1 Answers

You could make a timeout callback which recursively calls itself:

function x() {
  const array = [1, 2, 3, 4, 5, 6, 7, 8].slice(0, 5);
  function callback() {
    console.log(array.pop());
    if (array.length) setTimeout(callback, 1000); // change to 5000 in your actual code
  }
  callback();
}

x()

Another option, by awaiting a Promise that resolves after a few seconds inside the loop:

const delay = ms => new Promise(res => setTimeout(res, ms));
async function x() {
  const array = [1, 2, 3, 4, 5, 6, 7, 8].slice(0, 5);
  for (const item of array.reverse()) {
    console.log(item);
    await delay(1000);
  }
}

x()

Related