-1

This is a very simplified snippet code to illustrate the problem.

var srcs = ["url1", "url2", "url3"];

for (var i = 0; i < srcs.length; i++) {

    var img = document.createElement("img");

    var tryBrokeClosure = i;

    img.onload = function() {
        console.log(tryBrokeClosure);
    };

    img.src = srcs[i];
}

As you probably guessed, I was expecting:

0
1
2

But got:

2
2
2

So my question is: How can I safely pass the i variable to an async function without getting altered by the original scope?

EDITED:

I have this answer to a very similar question, but this answer use the creation of a function to break the closure, something that I can't do here.

Community
  • 1
  • 1
Jonny Piazzi
  • 3,684
  • 4
  • 34
  • 81

1 Answers1

1
img.onload = (function(i) {
  return function() {
    console.log(i);
  }
})(i);

or

img.onload = function(i) {
  console.log(i);
}.bind(img, i);
Yuriy Yakym
  • 3,616
  • 17
  • 30