While working with an API function that requires a callback in a for loop, I encountered an issue where the callback needed to be index-specific. However, I couldn't alter the willCallBack function (as it's part of the API) and didn't want to resort to using global variables.
The code snippet below demonstrates this challenge. The first for loop yielded unexpected results by returning i==4 for all callbacks. The second for loop provided a workaround, but it felt somewhat cumbersome and hacky.
I'm looking for a cleaner solution to pass the value of 'i' into the callback function definition without compromising on the functionality.
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);