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?
JavaScript
x
18
18
1
const reverseNumbers = (array) => {
2
const n = array.length;
3
return new Promise((resolve) => {
4
let res = [];
5
for (let i = n - 1; i >= 0; i--) {
6
setTimeout(() => {
7
console.log(array[i]);
8
res.push(array[i]);
9
if (i === 0) resolve(res);
10
}, 2000 * (n - i));
11
}
12
});
13
};
14
15
const array = [1, 2, 3, 4, 5];
16
let myPromise = reverseNumbers(array);
17
myPromise.then((res) => console.log(res));
18
Advertisement
Answer
Is there a better way to return an updated value after setTimeout?
Promisify setTimeout
on its own, then use async
/await
:
JavaScript
1
20
20
1
function delay(t) {
2
return new Promise(resolve => {
3
setTimeout(resolve, t);
4
});
5
}
6
async function reverseNumbers(array) {
7
const n = array.length;
8
const res = [];
9
for (let i = n-1; i >= 0; i--) {
10
await delay(2000);
11
console.log(array[i]);
12
res.push(array[i]);
13
}
14
return res;
15
}
16
17
const array = [1, 2, 3, 4, 5];
18
const myPromise = reverseNumbers(array);
19
myPromise.then(console.log);
20