jskidd3
jskidd3

Reputation: 4783

Break for loop inside closure

for (var e = 0; e < markers.length; e += 1) {
    (function (e, markers, latLngBounds) {
        if (latLngBounds.contains(markers[e])) {
            updatePrompt("Marker is contained");
            // Break for loop
        }
    })();
}

In the example above, after the updatePrompt method is invoked how can I break out of the loop containing the closure?

Upvotes: 1

Views: 616

Answers (3)

adeneo
adeneo

Reputation: 318182

var broken = false;

for (var e = 0; e < markers.length; e += 1) {
    if (broken) {
        break;
    } else {
        (function (e, markers, latLngBounds) {
            if (latLngBounds.contains(markers[e])) {
                updatePrompt("Marker is contained");
                broken = true;
            }
        })();
    }
}

A little verbose, but you get the point.

This could also be done with Array.some in modern browsers

markers.some(function(marker) {
    if (latLngBounds.contains(marker)) {
        updatePrompt("Marker is contained");
        return true;
    }
    return false;
});

Upvotes: 3

Korikulum
Korikulum

Reputation: 2599

Another way:

for (var e = 0; e < markers.length; e += 1) {
    if ((function (e, markers, latLngBounds) {
        if (latLngBounds.contains(markers[e])) {
            updatePrompt("Marker is contained");
            return 1;
        }
        return 0;
    })())
        break;
}

Upvotes: 0

Qasim Javaid Khan
Qasim Javaid Khan

Reputation: 660

not sure if i get you correct, but if you want to break the loop set e= markers.length;

The loop will not continue after this statement

Upvotes: 1

Related Questions