Search code examples
javascriptfor-loopsettimeout

Javascript setTimout in loop not working as expected


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.


Solution

  • 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);
    }