mike d
mike d

Reputation: 58

Access index of multiple callbacks instantiated in for loop

I am invoking an API function - which takes a callback - multiple times in a for-loop. My callback needs to do something index-specific. I can't change the willCallBack function (it is part of the API) and I want to avoid creating global variables.

The following snippet illustrates the problem. The first for-loop was my first attempt, but it returns i==4 for all callbacks. The second for-loop works - but it is ugly and feels 'hackish'

What is a cleaner way of getting the value of 'i' into the callback function definition?

var result = '', result2 = '';

// doesn't work; i == 4 for all
for(var i=0; i<4; i++) {
    willCallBack(function(msg) {
        result += msg + i + '\n';
    });
}

// works, but kinda ugly
for(var i=0; i<4; i++) {
    willCallBack(function(i) {
        return function(msg) {
            result2 += msg + i + '\n';
        };
    }(i));
}

// part of API, cant change
function willCallBack(cb) {
    window.setTimeout(cb, 500, "can't change me");
}

// show the results
window.setTimeout(function(){
        alert(result + '\n\n' + result2)
    }, 1000);

Upvotes: 2

Views: 100

Answers (1)

bfavaretto
bfavaretto

Reputation: 71939

The alternative to your "kinda ugly" version is to have a named function return the callback, instead of an anonymous, self-executing function. Maybe you'll find it less ugly?

for(var i=0; i<4; i++) {
    willCallBack(createCallback(i));
}

function createCallback(index) {
    return function(msg) {
        result2 += msg + index + '\n';
    };
}

Upvotes: 2

Related Questions