How do I access the globalBuffer
variable after setting it in the request.onload
callback? I'm learning more about closures, but don't understand why I'm unable to set the value and retrieve it after the fact. In other words, why does console.log(globalBuffer)
return undefined
?
var globalBuffer;
var context = new webkitAudioContext();
function loadSound(url) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
request.onload = function() {
context.decodeAudioData(request.response, function(buffer) {
// I want to set globalBuffer and retrieve it outside the function
globalBuffer = buffer;
}
);
}
request.send();
}
loadSound("http://upload.wikimedia.org/wikipedia/en/9/9e/Metallica_-_For_Whom_the_Bell_Tolls_%28song%29.ogg");
console.log(globalBuffer);
Edit: