DEV Community

Discussion on: Pass parameter to setTimeout inside a loop - JavaScript closure inside a loop

Collapse
 
jasperhorn profile image
JasperHorn • Edited

Note that you can use it, though it gets pretty hard to read in this situation:

for (var i = 0; i < arr.length; i++) {
  setTimeout(function (i) { return function() {
    console.log('Index: ' + i + ', element: ' + arr[i]);
  }}(i), 100);
}

There might be situations where that makes sense. I wouldn't know exactly which ones that would be (though I'm pretty sure the situation starts with "I can't use let").