I'm new to Javascript and trying to loop over the array inside a for loop with a setTimeout
this is a portion of code so i have 100msec by default.
I'm expecting output to be 1,2,3 but all its printing is undefined 3 times.
if someone can help me explaining why that will be helpful.
var allCars=['Car1','Car2','Car3'];
for(var i = 0; i < allCars.length; i++)
{
(function(temp){
setTimeout(function(temp){
console.log(allCars[temp]);
},100)})(i);
}
setTimeout
does not pass any parameter (unless you specify one) to its callback, but you're specifying one parameter named temp
, which hides the temp
in the outer scope.
var allCars=['Car1','Car2','Car3'];
for(var i = 0; i < allCars.length; i++)
{
(function(temp){
setTimeout(function(temp){ // This temp hides the temp on the line above
console.log(allCars[temp]);
},100)})(i);
}
Simply remove the parameter from the callback passed to setTimeout
to allow the outer temp
to be visible.