I’m trying to give the for loop parameter i to the inner closure because I want to identify my decoded audio (that’s put inside buffer).
This code gives an error: e is undefined. It works however when removing the )(test) by which I mean that test is equal to list.length for all the results however I want them to have the value of the current parameter i when called.
for (var i = 0; i < list.length; i++) { //load in every url
requestArray.push(new XMLHttpRequest());
requestArray[i].open('GET', list[i].url, true);
requestArray[i].responseType = 'arraybuffer';
test = i;
requestArray[i].onload = (function (e) {
//Async method: ASK J
context.decodeAudioData(e.target.response, (function (buffer) { //Async method
console.log(test);
if (!buffer) {
alert('error decoding file data: ');
return;
}
})(test),
function (e) {
console.log('Error decoding audio file', e)
});
})(test);
requestArray[i].onerror = function () {
alert('BufferLoader: XHR error');
}
requestArray[i].send();
}
Please note that for a closure to be created a function must return a function.
This is a closure:
This is evaluated AS SOON as it is seen: