Variable in JavaScript callback functions always gets last value in loop? [duplicate]

Solution 1:

The problem is that you are 'closing' over the same variable.

var does not declare a variable1. It simply annotates a 'stop look-up' for an identifier within a given execution context.

Please see Javascript Closures "FAQ Notes" for all the nice details. The sections on 'execution context' and 'scope chain' are most interesting.

The common idiom is perform a double-binding to create a new execution context.

E.g.

var k
for (k = 1; k < 10; k++) {
  setTimeout((function (_k) {
    return function () {
      alert(_k)
    }
  })(k), k * 100)
}

As of JavaScript 5th Edition there is Function.bind (it can also be implemented in 3rd edition such as bind from prototype.js), which can be used as such:

var k
for (k = 1; k < 10; k++) {
  setTimeout((function () {
     alert(this)
  }).bind(k), k * 100)
}

1 This construct is referred to as a Variable Declaration in the ECMAScript specification. However, this statements, as misleading as it may be viewed, is stressed to bring home a point: also see "variable hoisting".

Solution 2:

I also found this solution at http://meshfields.de/event-listeners-for-loop/:

var myArr = [0,1,2,3]; 

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

(function (i) { 

    document.getElementById('myDOMelement' myArr[i]).onclick = function () { 

        if (window.console.firebug !== undefined) { 
            console.log('myDOMelement' myArr[i]); 
        } 
        else { 
                alert('myDOMelement' myArr[i]); 
        } 
        }; 
    }) (i); 
}