I am implementing the setTimeout function inside 'for loop', which doesn't seem to work as expected.
Here's the codes I used:
var listItems = ['1','2','3'];
for(var i = 0 ; i < listItems.length ; i++){
setTimeout(function(){
console.log(listItems[i])
},500)
}
Tested, returns 'Undefined (3)'
Baffled, tried another solution
var listItems = ['1','2','3'];
for(var i = 0 ; i < listItems.length ; i++){
setTimeout(function(i){
console.log(listItems[i])
},500)
}
Obviously this wasn't even valid.
Looked on another similar question here, and tried:
var listItems = ['1','2','3'];
for(var i = 0 ; i < listItems.length ; i++){
(function(){
setTimeout(function(){
console.log(listItems[i])
},500)
})(i);
}
Still 'undefined(3)'
This is the working code without the setTimeout function. I am not sure what I am doing it wrong.
Thanks!