var linksList = [
"http://a.com",
"http://b.com",
"http://c.com",
]
for (var i=0; i<linksList.length; i++) {
setTimeout(function() {
console.log(linksList[i]);
}, 3000);
}
I’m pasting this into Chrome inspector and it returns a number for whatever reason (it seems to be an entirely random number?)… then it waits… and then returns 3 ‘undefined’ console errors.
Use closure:
Your problem is ,when
setTimeout‘s callback is called,i = linksList.lengthalready , so you are outputting:3times, wherelinksList[ linksList.length ]isundefined.