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

4
  • If not let or var... are you trying to use const? I guess I'm not sure what the goal is in not using let. Commented Jun 6, 2019 at 3:28
  • @stealththeninja probably to avoid using ES6+ Commented Jun 6, 2019 at 3:30
  • @stealththeninja I mean just use var Commented Jun 6, 2019 at 3:30
  • Another way using recursion and no simultaneous timeouts. Commented Jun 6, 2019 at 3:55

1 Answer 1

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();

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.