Skip to content
Advertisement

How to print an array updated by setTimeout? [closed]

The task is to write a function to reverse an array of numbers and print out each number every 2 seconds. Also print the reversed array in the end.

I wrote the following to achieve this, but it is a bad method, since I need to calculate the number of seconds in each setTimeout and also take extra steps to determine whether the for loop has reached the last iteration.

Is there a direct way to pause 2 seconds after each iteration and then print the reversed array in a synchronous way?

const reverseNumbers = (array) => {
  const n = array.length;
  return new Promise((resolve) => {
    let res = [];
    for (let i = n - 1; i >= 0; i--) {
      setTimeout(() => {
        console.log(array[i]);
        res.push(array[i]);
        if (i === 0) resolve(res);
      }, 2000 * (n - i));
    }
  });
};

const array = [1, 2, 3, 4, 5];
let myPromise = reverseNumbers(array);
myPromise.then((res) => console.log(res));

Advertisement

Answer

Is there a better way to return an updated value after setTimeout?

Promisify setTimeout on its own, then use async/await:

function delay(t) {
  return new Promise(resolve => {
    setTimeout(resolve, t);
  });
}
async function reverseNumbers(array) {
  const n = array.length;
  const res = [];
  for (let i = n-1; i >= 0; i--) {
    await delay(2000);
    console.log(array[i]);
    res.push(array[i]);
  }
  return res;
}

const array = [1, 2, 3, 4, 5];
const myPromise = reverseNumbers(array);
myPromise.then(console.log);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement