0

Why isn't setTimeout working inside the for loop?

why isn't the code given below not working? for(var i = 0 ; i<5 ; i++){ setTimeout(()=>{ console.log(i); },1000 * i); } // outputs 5,5,5,5,5 one by one. But this one works fine. why? for(var i = 0 ; i<5 ; i++){ x(i); } function x(i){ setTimeout(()=>{ console.log(i); },1000 * i); } // outputs 0,1,2,3,4 one by one

16th Sep 2021, 7:08 AM
Mons Joseph
Mons Joseph - avatar
2 Réponses
0
According to my understanding , var is function scoped variable . In the first one i is global so the final value of i is taken ! In second one, well you have a function which captures the right value. And that value is local to it. ps: there are let and const variables also which are block scoped. so changing first one to "let i" will work fine. Wait for others explanation though since i have a bit of confusion on it myself.
16th Sep 2021, 7:52 AM
Abhay
Abhay - avatar
0
You need to pass the variable i to setTImeout and then pass i to the anonymous callback. for(var i = 0 ; i<5 ; i++){ setTimeout((i)=>{ console.log(i); },1000 * i, i); } // outputs 0,1,2,3,4 one by one.
18th Sep 2021, 2:03 PM
ODLNT
ODLNT - avatar