0

My delayed for loop keeps returning "-1" no matter what i do.

for (var i = 5; i > 0; i--) {
    setTimeout(function() {
        console.log(i)
    }, i * 1000)
}

(i changed my variable to 5)

Krupesh Kotecha
  • 2,396
  • 3
  • 21
  • 40

1 Answers1

1

The simplest way will be to call a function inside the for and let that function handle the setTimeout

for (var i = 5; i > 0; i--) {
  fnSetTimeout(i);
}     
            
function fnSetTimeout(i) {
 setTimeout(function() { console.log(i); }, 1000 * i);
}
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62