joehungjohn joehungjohn - 1 month ago 7
Javascript Question

Why can't I break out of this for loop?

This is a test for a site where I check if photo sources exist or not, if they don't I want to hide the extra panel that would show these photos if they exist. The problem is I can't get the

breakVar = true;
state to come out and the loop won't stop either, I've tried different ways to get it to stop with breaks/returns.

I test for the output of
testPhotos(currentProduct,display,breakVar);
and I want to get a "test-fail" return so I can hide the extra panel.

yeah the code kind of became ugly as I desperately tried to check states in progress of code execution.

I've tried putting the
break;
statement in different places but get "Illegal break statement" error

I get test failed in loop 8 times in my console.

var breakVar = false;

function triggerPhotoFail(breakVar) {
breakVar = true;
consol.log('triggerPhotoFail ran');
return "test-fail";
}
function testPhotos(currentProduct,display,breakVar) {
for (var i = 0; i < 5; i++) {
// test if photos exists
if (breakVar === true) {
break; // get out of loop
}
var src = productArray[currentProduct]['subphoto-' + i];
$.get(src)
.done(function() {
// photo exists
})
.fail(function(breakVar) {
// photo does not exist
console.log('test failed in loop');
breakVar = true;
triggerPhotoFail();
console.log('breakVar change!: ' + breakVar);
})
}
if (breakVar === true) {
console.log('breaker var tested true');
return "test-fail";
}
else {
return "not acknowledged";
}
}

Answer

$.get is asynchronous. The loop has finished before the done or fail function has been called.

You need to replace the for loop with an iterator that gets advanced when the done function fires.

function testPhotos(currentProduct, display) {
  // This starts the loop
  var i = 0; next();

  function next() {
    // This replaces the regular "end of for loop" check
    if (i == 5) {
      return;
    }

    $.get(src)
      .done(function() {
        // photo exists
        i++; next(); // This does the "End of for loop increment" test and starts the next loop
      })
      .fail(function(breakVar) {
        // photo does not exist
        console.log('test failed in loop');
        triggerPhotoFail();
        // We don't call `next()` here, which breaks the loop
      });

  }
}
Comments