I placed an asynchronous callback function (something like $.ajax
) inside a for
loop. It looked more or less like (edit: updated code, see comments):
var i = 0;
for ( ; i < 5; i++ ) {
(function( index ) {
$.ajax({
url: "",
success: function() {
console.log( index );
}
});
})( i );
}
It worked, but JSHint gave me a warning saying something like:
"Don't place functions inside loops"
Normally I could just place my callback
function outside my loop and call that function for every iteration. Unfortunately I need access to variables, which are assigned inside the loop (e.g. i
). So I'm looking for a solution to do something like below:
var i = 0;
function callback( data ) {
// I want to have access to "i" (0, 1, 2, 3, 4) and the AJAX "data"
// in this function. But I only have access to "data", because "i"
// will always be 5
}
for ( ; i < 5; i++ ) {
$.ajax({
url: "",
success: callback
});
}