3

I am learning JavaScript and am quite new in Programming and happened to land upon these infinite loops which were said to go on forever and crash the browser, but when I created one with these codes:

i=0;
while (i<10) {document.write(i);}

The browser just kept on going to load it and never did but the browser didn't crash?
So is it that the browsers these days are powerful enough to withstand infinite loops, or do I need a different infinite loop?

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Abhishek Mhatre
  • 535
  • 2
  • 9
  • 15
  • You could try an infinite loop that adds information to an array. – Sanchit Jan 07 '13 at 11:04
  • Did you get any javascript errors? – Leandro Barreto Jan 07 '13 at 11:18
  • "withstand infinite loops" - there is a difference between "infinite loop" and "continuous processing". I assume you're interested in the latter. In that case search for setTimeout function and see how you can partition your work in correct chunks – Liviu T. Jan 07 '13 at 11:48

1 Answers1

11

Yes, Infinite loops do still crash browsers (Or just the tab the JS is running in). However, most modern browsers can detect if a script's hanging / running a infinite loop, and give you the option to abort the script.

Also, a more efficient way to create a infinite loop, would be:

while(true);
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • 1
    That is the one thing about JS I will never understand: why an infinite loop freeze the whole page instead of just... *running*, like every other environment/language in existence where infinite loops are fair game. I really don't see why the interpreter can't just sit in a separate thread while the renderer listens for changes to the DOM and applies them on a first come, first serve basis. I could understand blocking *future scripts* from executing, but not the *renderer*. – Braden Best May 31 '17 at 05:19
  • because the model used (defined in the world wide web consurtium) is single threaded by default, and clicking a DOM node can trigger a function, that needs to be executed after what is executing right now to be predictable, the "after" never comes with infinite loops. Web workers and timeInterval can be used to overcome some of the limitations – Walle Cyril Nov 11 '17 at 16:25