Often, when a program is run and the browser becomes unresponsive and crashes, this means that your program contains an infinite loop.

Infinite loops occur when loops have no exit condition - no way to stop - so when the program is run it loops forever with no break, causing the browser to crash. This happens most often with while loops, but any kind of loop can become infinite. Learn more about infinite loops.

Debugging Infinite Loops

The best first step for debugging an infinite loop is to comment out different sections or lines of code, then running the program to see where the infinite loop is occurring. Start by testing any sections that contain for or while loops, then if/else statements, then other blocks of code.

Once the program runs successfully, you know that your infinite loop is in the commented section of code. Check the code carefully to make sure that it contains a condition that will cause the loop to stop. For example:

  • In a while loop, will the condition get to false to break the loop?
  • In a for loop, does i increment correctly?
  • In an if/else statement, are all possibilities accounted for?

Each time you make a change to your code, running the code again will show whether they have successfully debugged the loop!

Still have questions on debugging?! Ask your teacher for help or check our these helpful tips on debugging code.

Did this answer your question?