programming
coding-practices
infinite-loops
software-development
code-optimization

Are while(true) loops bad practice?

Codemia Knowledge Hub ·

No. A while(true) loop is a reasonable choice for servers, daemons, event listeners and input prompts that run until something tells them to stop. It becomes a problem when the exit condition is buried or missing, when the loop busy-waits and burns CPU, or when it leaks resources on each pass.

How a while(true) loop ends

The condition is always true, so the loop only stops through logic inside the body (a break, a return) or an external interruption. Its basic form:

python
while(True):
    # Code block
    pass

Each iteration checks the condition, which never fails, so the body keeps running. Termination is handled by if checks inside the body that break out. A typical example:

python
1while True:
2    user_input = input("Enter 'q' to quit: ")
3    if user_input.lower() == 'q':
4        print("Exiting the loop.")
5        break
6    else:
7        print("You entered:", user_input)

Where while(true) fits

The loop gives a simple structure for repeated work with no predefined iteration limit. That suits:

  • Event listeners: systems waiting for events with no fixed endpoint.
  • Servers and daemons: processes that run indefinitely, handling incoming data or requests.
  • User interaction: programs that keep prompting until a specific input arrives.

It can also avoid the overhead of evaluating a more complex loop condition on every pass, in simple cases where external interruptions decide when to stop.

What goes wrong with while(true)

  • CPU usage: an uncontrolled loop runs without rest and can peg the CPU unless it sleeps or waits.
  • Memory leaks: resources that are not released inside the loop accumulate.
  • Hard debugging: the exit logic lives inside the body, so nested breaks and conditions are harder to follow and maintain.
  • Reduced readability: other developers have to read the whole body to learn when the loop stops.
  • Infinite loops: without a working halting mechanism, the application hangs or crashes.

Writing a safe while(true) loop

  • Explicit exit conditions: keep them clear and simple.
  • Resource management: release resources and handle exceptions inside the loop.
  • Timeouts: stop waiting if conditions are not met within an expected time.
  • Sleep intervals: pause between cycles when continuous looping is not needed.
python
1import time
2
3while True:
4    try:
5        # Some processing
6        data = fetch_data()
7        if data:
8            process_data(data)
9        else:
10            time.sleep(5)  # Sleep to reduce CPU usage and resource strain
11    except Exception as e:
12        print("Error encountered:", e)
13        break  # Break on critical failure

Alternatives to while(true)

  • For loops with conditional breaks: when the iteration count is known or can be determined.
  • Event-driven designs: event listeners or callbacks instead of a perpetual loop.
  • State machines: finite state machines for complex, nested condition logic, where explicit states and transitions are easier to manage.

while(true) at a glance

Key PointsDetails
AdvantagesFlexibility & simplicity Ideal for event-driven tasks
DrawbacksResource consumption Complexity & debugging challenges
Best PracticesUse explicit exit conditions Introduce timeouts & sleeps
AlternativesConditional 'for' loops State machines & event-driven design

Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms