closure inside a for loop – callback with loop variable as parameter [duplicate]

This is a pretty standard problem with closures. When you do this:

function(data, textStatus) { test(data, textStatus, idx); }

You’re binding a reference to idx but not to the value of idx. So, by the time your callback gets called, the loop will have finished and idx will be 16 in all of the callbacks that you bound.

The usual solution is to force evaluation of idx through a function call:

function build_callback(idx) {
    return function(data, textStatus) {
        test(data, textStatus, idx);
    };
}

// And then...

jQuery.get("svGetPortInfo.php?svSiteIpAddr=" + probeIP+"&s="+idx, build_callback(idx), 'text');

You can also inline the function with a self-executing function if you want to keep it all together:

for (var idx=1; idx<=15; idx++)
    (function(idx) {
        var probeIP = siteConfigArray[idx].siteIP;
        if (probeIP != "" && probeIP != null)
            jQuery.get("svGetPortInfo.php?svSiteIpAddr=" + probeIP+"&s="+idx, 
                function(data, textStatus) { test(data, textStatus, idx); }, 'text'); 
        else // IP value is blank
            siteConfigArray[idx].portManifest = null;
    })(idx);

The function call gives you the value of idx when the function is called and that’s the value of idx that you want.

Leave a Comment