1

Are there other reasons? What if they are too long? Will that make the browser crash, if so how long is too long?

Could a long looping crashing problem be solved with a setTimout 0 loop so code is executed every next tick and if this is the case, would it also be possible to loop infinitely in this manner and never crash?

I am not coding something this stupid sounding, I have just always wondered.

I would have thought it is different on each browser, so for the sake of the question lets say it is a reasonably well known and used browser - Chrome.

EDIT: The garbage collector and objects not being destroyed has been mentioned, does someone have an example of this?

8DK
  • 704
  • 1
  • 5
  • 15
  • Related: [how to avoid blocking the browser while doing heavy work?](http://stackoverflow.com/q/10180391/710446) Also, regarding "too long" versus "infinite", how could a program distinguish between a loop that terminates sometime after the heat death of the universe versus [a loop that will never terminate](https://en.wikipedia.org/wiki/Halting_problem)? You can always keep running the script (as long as the loop doesn't consume memory) but every modern browser will eventually offer the user the option to terminate the script early. – apsillers Jan 29 '15 at 13:01

2 Answers2

1

Time itself is not a constraint, but rather what you do within the loop. For example if you create many objects within loops which are not destroyed by garbage collector you will eventually run out of memory and crash the script.

Example:

var a = [];   
for (i = 0; i < Number.MAX_SAFE_INTEGER; i++) {
   a.push(a);
}

(Ok, it's a for loop, but can be rewritten to while and work just the same)

Mchl
  • 61,444
  • 9
  • 118
  • 120
  • is this an example of a safe loop, or a loop with no garbage collection? – 8DK Jan 29 '15 at 13:09
  • It's an example that will crash after some time because `a` object will grow to an enormous size – Mchl Jan 29 '15 at 13:11
  • Can you show an example of many objects within loops which are not destroyed by garbage collector? – 8DK Jan 29 '15 at 13:18
  • Just replace `a.push(a)` with `a.push({})`. This crashes my Chrome within a minute or so. – Mchl Jan 29 '15 at 13:42
0

If you have a Loop like this:

while(true)
{
  i = 1;
}

Nothing will happen, only CPU will get hot and the Browser will ask at some time to stop the script :D

If you have a recusive Loop or an Loop with some output, than yes the RAM is not invinit.

setTimout can save you resurces and doesn't block your website (so the browser will not ask you to stop it) but also, if its using the RAM with some outputs, it will fill the RAM.

timeout is doing co-operative multi-tasking

schnawel007
  • 3,982
  • 3
  • 19
  • 27