Maximum call stack size

2

It's a question that has more to do with curiosity, to understand how it works.

I know that if I call a function within itself indefinitely I get the error Uncaught RangeError: Maximum call stack size exceeded .

Initially, I thought there was a programmed limit on how many times the function would be called, and then I made the following snippet to test how many times the function runs before it causes the error:

i = 0
function a() {
    i++;
    try{ 
        return a()
    } catch(e) { 
        console.log(i);
        i = 0;
    }
}
Until then, okay. But when I run a(); multiple times, it prints me different numbers in each execution. And something I've noticed is that, running% c_de% multiple times quickly increases the number of attempts before reporting the error (from 20968 to 35945).

I tested on another machine, and the amount of attempts was different as well.

So here's the question: How do I set the number of times I run before I acknowledge the error?

    
asked by anonymous 31.10.2018 / 18:17

1 answer

3

There is no fixed number.

Have you noticed the name of the website? Stack Overflow? This is exactly what is happening in your browser. Each time the function is called, the browser allocates more and more memory in the stack to execute the new function. Since the function is being called recursively, there is no way to clear the previous functions from memory, since they are still running, waiting for the recursively called functions to return.

Eventually the stack will have no more space to allocate more data, with a stack overflow.

At most: the limit depends on how much memory is already allocated on the stack, and how much memory is needed to allocate its function on the stack.

    
31.10.2018 / 18:35