I'm having trouble breaking out of a for loop.
Right now, the loop does a jQuery getJSON call on every page. If the page has data, it logs all the items. If the page doesn't have data, the loop should stop entirely.
However, whenever I run this, it loops through all 100 pages. Once hitting a page with no data, it logs "this page has no content" but continues to run the for loop. (Thus ending up with an endless stream of "this page has no content" in my console)
What am I doing wrong?
I want to avoid throwing an i = NOTANINTEGER
to stop the loop
for (var i=0; i< 100; i++)
{
var breakForLoop = false;
var API = "http://www.foo.com/bar.json?page=" + i;
$.getJSON(API, function(data) {
var items = {};
// logs items from page run only when the page has data
if (data.length > 0) {
$.each( data, function(i, item) {
console.log(item.text);
});
}
// the page has no data, therefore remainder pages have no data too
else {
console.log("this page has no content");
breakForLoop = true;
return;
}
});
if (breakForLoop) {
break;
}
}