Alert causes infinite loop warning, stops code from running

Alert causes infinite loop warning, stops code from running
0

#1

Tell us what’s happening:
If I run my code with the alert commented out, then code works fine, and I’m invited to submit the code and to on to the next challenge. But if the alert isn’t commented out, then I get only the first one or two alerts (it varies), and the console displays this message:
Error: Potential infinite loop at line 7. To
disable loop protection, write:
// noprotect
as the first line. Beware that if you do have
an infinite loop in your code this will crash
your browser.

Why does the alert mess up the code’s logic? Thanks.

Your code so far

function findLongestWord(str) {
  var wordArray = str.split(' ');
  var maxLength = 0;
  
  for (var i=0; i < wordArray.length; i++) {
    if (wordArray[i].length > maxLength) {
      maxLength = wordArray[i].length;
    }
    alert(maxLength);
  }
  return maxLength;
}

findLongestWord("The quick brown fox jumped over the lazy dog");

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:48.0) Gecko/20100101 Firefox/48.0.

Link to the challenge:
This is in the “Find the Longest Word in a String” challenge in “Basic Algorithm Scripting”, at https://www.freecodecamp.org/challenges/find-the-longest-word-in-a-string.


#2

alert() blocks the execution of the code. I think you get the infinite loop warning because from the browser’s perspective, the blocked code in the loop looks like a potential infinite loop (because it takes too long for the loop to finish).

console.log() is a better alternative.