0

I want to print the array in descending order with a setTimeout. I don't know why the below code is not working in descending order.

let delay = 1000;
let array = [1, 2, 3, 4, 5];
for(let i = array.length; i > 0; i--) {
      setTimeout(() => {
        console.log(array[i - 1]);
      }, delay * i);
}

Expected output is 5 4 3 2 1 with one second delay. But it's printing 1 2 3 4 5 If I remove the i from setTimeOut() it will output as expected but won't work with the delay.

Really appreciate the help. Thanks.

Jamiec
  • 133,658
  • 13
  • 134
  • 193
Rejin Jose
  • 41
  • 6
  • Does this https://jsfiddle.net/db5cghna/ and this https://jsfiddle.net/db5cghna/1/ help? –  Jun 30 '21 at 12:55
  • 5
    At every cicle you're setting the delay like this: `delay * i`, with `i` ranging from 5 to 1. That means your timeouts will expire in reverse order: 5000 (set at the first cycle) will expire after 4000 (set at the second cycle) and so on. The first timeout to expire will be the one set at the last cycle (1000). – lbsn Jun 30 '21 at 13:00
  • @jabaa Yea, thank you. – Rejin Jose Jun 30 '21 at 14:00
  • @Ibsn, Thanks. I understand the mistake. Thankyou. – Rejin Jose Jun 30 '21 at 14:01

2 Answers2

0

It's bcz you say to JS print "5" after five seconds, then print "4" after four seconds then print "3" after three seconds and so on... Actually the code is just doing what you said. You can do something like this

let delay = 1000;
let array = [1, 2, 3, 4, 5];
for(let i = array.length, j = 0; i > 0; i--, j++) {
      setTimeout(() => {
        console.log(array[i - 1]);
      }, delay * j);
}
utkuonursahin
  • 249
  • 4
  • 10
0

i think it's something like that that you want to do :

let delay = 1000;
let array = [1, 2, 3, 4, 5];
for(let i = array.length; i > 0; i--) {
      setTimeout(() => {
        console.log(array[i - 1]);
      }, delay * (array.length - i));
}
Lk77
  • 2,203
  • 1
  • 10
  • 15