I'm trying to break a for-loop (labeled) from within a nested anonymous function, like this:
function ajax(iteration, callback) {
var rtrn, xh;
if (window.XMLHttpRequest) {
xh = new XMLHttpRequest();
} else {
xh = new ActiveXObject("Microsoft.XMLHTTP");
};
xh.onreadystatechange = function() {
if (xh.readyState == 4 && xh.status == 200) {
callback(xh.responseText);
};
};
xh.open("GET", "file.php?i=" + iteration, true);
xh.send();
};
var atk_delay = 100;
loop:
for(i = 1; i <= 40; i++) {
var to = atk_delay * i;
setTimeout(
function() {
ajax(i, function(responseText) {
var div = document.getElementById("combat");
div.innerHTML += responseText;
var arrRt = responseText.split("::");
if(arrRt[0] == "stop") {
break loop;
};
});
},
to);
};
I really have no idea how to solve this. Obviously, the problem is that it cannot find the label. How can I resolve this?
setTimeoutandajaxare obviously asynchronous, the logic inside the callback occurs after the loop has finished, andigets lost due to the new scope. So there are two problems here, the "Infamous JavaScript Loop Problem" and the "How to return the response from an AJAX call"stop