简体   繁体   中英

settimeout inside a loop doesnot print the value of variable?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM