Skip to main content

Infinite loop

Short answer

If a function has an infinite loop, JavaScript will never free the call stack, and the event loop will stop - no other tasks (timers, promises, clicks, UI repaints) will be able to run. As a result, the page "hangs".


Example

javascript
function infinite() { while (true) { console.log('forever...'); } } infinite();

What happens:

  1. The infinite() function lands on the call stack.
  2. The while (true) loop starts running - it never finishes.
  3. The engine never exits the function, so:
  • the stack never frees up,
  • the event loop can't pick up the next task,
  • the browser stops responding (clicks, scrolling, even DevTools can "freeze").

Why this happens

JavaScript is a single-threaded language. It can run only one piece of code at any given moment (whatever is on the call stack).

Until the function finishes, the engine won't switch to other tasks, whether that's setTimeout or Promise.then.


Example with a timer (that will never fire)

javascript
setTimeout(() => console.log('I will not run'), 0); while (true) {} // infinite loop

Explanation:

  • setTimeout puts the callback into the macrotask queue;
  • But while while(true) is running, the stack does not free up;
  • The event loop cannot take a task from the queue;
  • console.log('I will not run') never executes.

Summary

ConsequenceDescription
Stack blockedCode never exits the function -> the stack never frees up
Event loop stopsTask queues (timers, promises) are not processed
Page hangsThe UI doesn't repaint, the browser may show "Page unresponsive"
No response to eventsClicks, scrolling, input don't work

How to avoid blocking

Use asynchrony or break work into chunks:

Option 1: setTimeout

javascript
function loop() { console.log('iteration'); setTimeout(loop, 0); // gives the engine a "breather" } loop();

Option 2: requestAnimationFrame

Good for visual tasks (animations):

javascript
function animate() { // draw a frame requestAnimationFrame(animate); } animate();

Option 3: Web Worker (if you need heavy computational logic)

Move the computation to a separate thread:

javascript
// worker.js onmessage = e => { while (true) {} // can run long - the UI won't hang };

Conclusion

TermExplanation
Infinite loop in a functionNever exits the call stack
ConsequenceThe event loop blocks, the browser "freezes"
SolutionSplit work into chunks (setTimeout, requestAnimationFrame, Web Workers)

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.