DEV Community

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

Collapse
mingyena profile image
Rae Liu Author • Edited on

Thank you Jasper! Yes, it doesn't make sense to use IIFE for setTimeout. I am going to add a note on Solution 1.

Collapse
jasperhorn profile image
JasperHorn • Edited on

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").