DEV Community

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

Collapse
 
jasperhorn profile image
JasperHorn

I'm not sure the code for example 1 is correct.

The code as currently written, logs things right away and then when the timeout is over, it does nothing. This isn't too obvious when the timeout is 100ms, but it becomes a lot clearer when you set a larger timeout. (With an extra function (){ before the function and an extra } that type of solution can be made to work nonetheless.

Collapse
 
mingyena profile image
Rae Liu • Edited

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

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