SOQ: 10388791 - Variable in use by ajax 'success' callback in 'for' loop

demo of how lexical scoping and closure can cause 'odd' behaviour when using a success callback within ajax.

by robcthegeek

HTML

<ul id="output">

</ul>

JavaScript

function correctOutputPlox(id) {
 // simulate some ajax activity...
 setTimeout(function() {
   $("#output").append("<li>" + id + "</li>");
 }, 500);   
}

function runNicely() {
    // same loop...
    for (var x = 0; x < 10; x++) {
        // but rather than use 'x' (which is going to change, we pass it's value into a function which doesn't have access to the original 'x' since it's in a different lexical scope.
        correctOutputPlox(x);
    }
}

function showProblem() {
    for (var x = 0; x < 10; x++) {
        setTimeout(function() {
            $("#output").append("<li>" + x + "</li>");
        }, 500);
    }
}

showProblem();
runNicely();