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:
- The
infinite()function lands on the call stack. - The
while (true)loop starts running - it never finishes. - 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 loopExplanation:
setTimeoutputs 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
| Consequence | Description |
|---|---|
| Stack blocked | Code never exits the function -> the stack never frees up |
| Event loop stops | Task queues (timers, promises) are not processed |
| Page hangs | The UI doesn't repaint, the browser may show "Page unresponsive" |
| No response to events | Clicks, 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
| Term | Explanation |
|---|---|
| Infinite loop in a function | Never exits the call stack |
| Consequence | The event loop blocks, the browser "freezes" |
| Solution | Split work into chunks (setTimeout, requestAnimationFrame, Web Workers) |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.