Debugging Infinite Loops

How to fix code that causes the browser to time out, freeze, or crash

Jeremy Keeshin avatar
Written by Jeremy Keeshin
Updated over a week ago

Often, when a program is run and the browser becomes unresponsive and crashes, it means that the 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 loops by checking out this tutorial.

Image demonstrating an infinite loop in Python

Debugging Infinite Loops

The best first step for debugging an infinite loop is to comment out different sections or lines of code. Next, run the program again 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-out section of the 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 students make a change to their code, running the code again will show whether they have successfully debugged the loop!

โ€‹Still have questions? Contact our team at to learn more!

Did this answer your question?