Often, if your browser becomes unresponsive or crashes after running or checking a program, it means that the code contains an infinite loop.
Infinite loops occur when loops have no exit condition, or no way to stop. 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.
Remember, debugging is at the heart of programming! Every programmer will write programs with errors and each one is a chance to learn!
🔁 What an infinite loop looks like
Let's take a look at this Python code:
The value of i
is set at zero, and never changes, so i
will ALWAYS be less than 10. That means that the print
statement will run INFINITELY. 😱
This will cause our Chrome browser to freeze and/or crash:
An infinite loop can also cause any other buttons on your screen to become non-responsive.
➡️ If you notice your "check code" button is not working, you may have an error in your code or an infinite loop!
🪲Debugging Infinite Loops
The best first step for debugging an infinite loop is to comment out different sections or lines of code, then run 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 the code. Check the code carefully to make sure that it contains a condition that will cause the loop to stop.
Example questions to ask:
In a
while
loop, will the condition get to false to break the loop?In a
for
loop, doesi
increment correctly?In an
if/else
statement, are all possibilities accounted for?Could I use a
break
orcontinue
statement in mywhile
loop?
Each time you make a change to your code, running the code again will show whether you've successfully debugged the loop! 💪
🐞More Debugging Skills
If you are interested in learning more debugging skills, check out our tutorials here:
Still have questions on debugging?! Ask your teacher for help!