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

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”.

Leave a Comment