DEV Community

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

Collapse
 
lexlohr profile image
Alex Lohr

Solution 4: use the closure from the setTimeout callback:

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

Warning: does not work in Internet Explorer.

Collapse
 
mingyena profile image
Rae Liu • Edited

Thank you Alex, I was thinking about setTimeout callback! For other functions, is it better to create a separate callback function?

Collapse
 
lexlohr profile image
Alex Lohr

I only added it for the sake of completeness.

While I really like the ability to control scope in ES6 and therefore would probably prefer to use let, for most loops, I would be using forEach or one of its brethren methods in any case, so using let instead would not improve legibility.