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. The difficult part is the print the reversed array in the end.
I wrote the following to achieve this, but it seems a bit convoluted. Is there a better way to return an updated value after setTimeout, or this is the expected method?
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));
CodePudding user response:
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);
CodePudding user response:
Here is another way of doing it. No idea, whether this is shorter or better, but in any case: it works.
function rev(arr){
let r=arr.slice(0),
intv=setInterval(()=>{
if(r.length) console.log(r.pop());
else {
clearInterval(intv);
console.log(arr.reverse())
}
}, 2000);
}
rev([0,8,15,47,11]);