2
let timer = () => {
  for(let i = 0; i < 5; i ++) {
    setTimeout(() => {
      console.log(i)
    }, i * 1000)
  }
}
timer();

code above will print 0, 1, 2, 3, 4 in 1000ms interval
and if I change let i = 0 into var i = 0, timer() will pring '5' five times in 1000ms interval. So far so good, and I know the differences between let and var
But now I want to print 0, 1, 2, 3, 4 in 1000ms interval, and not using let keyword, so what should I do?
I think I might need to use closure, but I don't know how.
edit: by not using let I mean use var instead

yuan
  • 1,701
  • 2
  • 13
  • 24

1 Answers1

0

If you can't use let, you can always use an Immediately Invoked Function Expression:

let timer = () => {
  for (var i = 0; i < 5; i++) {
    (i => {
      setTimeout(() => {
        console.log(i)
      }, i * 1000)
    })(i)
  }
}
timer();

If you're trying to make your code ES5-compatible, you've got to turn the arrow functions into normal functions as well:

var timer = function () {
  for (var i = 0; i < 5; i++) {
    (function (i) {
      setTimeout(function () {
        console.log(i);
      }, i * 1000);
    })(i);
  }
}
timer();
Angel Politis
  • 10,955
  • 14
  • 48
  • 66