scope of variables in JavaScript callback functions

You’re sharing the single i variable among all of the callbacks.

Because Javascript closures capture variables by reference, the callbacks will always use the current value of i. Therefore, when jQuery calls the callbacks after the loop executes, i will always be 2.

You need to reference i as the parameter to a separate function.

For example:

function sendRequest(i) {
    $.get('', function() {

for (var i = 0; i < 2; i++) {

This way, each callback will have a separate closure with a separate i parameter.

Leave a Comment