0

I'm trying to run a for loop and print the current index without use let

here my code:

function init() {
  for (var index = 0; index < 5; ++index) {
    setTimeout(() => {
      console.log(index);
    }, index);
  }
}

I expected to: 0 1 2 3 4 but i get 5 5 5 5 5

Once the Var replace in Let the problem will be solved

I want to stay with Var

How can the problem be solved? Thanks

galhayne
  • 3
  • 2

1 Answers1

0
function init() {
  for (var index = 0; index < 5; ++index) {
   const i = index;
   setTimeout(() => {
    console.log(i);
   }, i);
  }
 }

This should work.

Ampit
  • 51
  • 3
  • it is posible to stay with timeout and get the index? – galhayne Nov 02 '22 at 21:36
  • not sure, You could also use setInterval if you want something to run continuosly after a certain amount of delay. maybe that'll work for you. – Ampit Nov 02 '22 at 21:42