2
function x(){
    for(var i=1;i<=5;i++){
        setTimeout(function (i){
            console.log(i)
        },i*1000)
    }
}
x();

here is my code can anyone help me out why my code is printing """"undefined""" in place of i

I've been searching how to use the setTimeout function inside a loop but the documentation about this stuff seems limited, I want to make a setTimeout inside a for loop. it would be great if you help me out with this

  • 2
    the parameter in `function (i)` shadows the outer variable `i`. But see [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/q/750486) for more on the actual thing you're trying to do. – VLAZ Nov 20 '22 at 10:11
  • First, remove the unused argument `i` as it will shadow the outer `i` but it's never set so it's `undefined`. Then, replace `var` by `let` and it will work. [Here is why.](https://www.youtube.com/watch?v=Nzokr6Boeaw) – CherryDT Nov 20 '22 at 10:22

1 Answers1

1

You can follow how-can-i-pass-a-parameter-to-a-settimeout-callback to pass paramerter to setTimeout()

Also need to use let i=1;i<=5;i++ instead of var i=1;i<=5;i++ to narrow the scope of i

function x(){
    for(let i=1;i<=5;i++){
        setTimeout(function (){
            console.log(i)
        },i*1000)
    }
}
x();
flyingfox
  • 13,414
  • 3
  • 24
  • 39