Jonny Piazzi Jonny Piazzi - 1 month ago 13
Javascript Question

Work around scope closure in async call

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.

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

or

img.onload = function(i) {
  console.log(i);
}.bind(img, i);