Christian Lundahl
Christian Lundahl

Reputation: 2060

Break a for loop from within an anonymous function

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?

Upvotes: 1

Views: 832

Answers (3)

Elle
Elle

Reputation: 157

A simple hack to debug anonymous blocks - call the debugger explicitly before the line you want to examine.

function foo().then(s => {
  ... some code
  debugger // here your code will break. 
  someVariableIwantToExamine
}

Upvotes: 0

Christian Lundahl
Christian Lundahl

Reputation: 2060

So I solved it! Thanks for the help guys! You got me to realize I needed a completely different approach!

function ajax(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", true);
    xh.send();
};

var atk_delay = 100;

function roll() {
    ajax(function(responseText) {
        var div = document.getElementById("combat");
        div.innerHTML += responseText;
        var arrRt = responseText.split("::");
        if(arrRt[0] == "cont") {
            setTimeout(roll, atk_delay);
        };
    });
};

setTimeout(roll, atk_delay);

Upvotes: 1

Travis
Travis

Reputation: 10547

Normally what you would do is have a variable that's accessible after each iteration of the loop that would indicate if you can break. This would be set in the anonymous function.

However, in your specific case, since you are calling setTimeout, execution of the loop might have been completed by the time you can even set the value. setTimeout schedules the function to later execution (in ms).

You can use a variable to exit the anonymous function early if something has flagged it as done.

Upvotes: 0

Related Questions