Size of "Maximum call stack"

Asked

Viewed 558 times

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 it itself indefinitely I get the error Uncaught RangeError: Maximum call stack size exceeded.

Initially, I thought there was a programmed limit of how many times the function would be called, and then I did the following snippet to test how many times the function runs before causing the error:

i = 0
function a() {
    i++;
    try{ 
        return a()
    } catch(e) { 
        console.log(i);
        i = 0;
    }
}

So far, so good. But when executing a(); multiple times, it prints me different numbers at each run. And one thing I noticed is that, run a(); Several times quickly, increases the number of attempts before the error (from 20968 to 35945).

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

So the question follows: How is the number of times executed before the error is set?

  • Cool question, let’s see what the experts say kk

1 answer

3


There is no fixed number.

Have you noticed the name of the site? Stack Overflow? That’s exactly what’s happening in your browser. Each time the function is called, the browser allocates more and more memory on the stack (stack) to perform the new function. As the function is being called recursively, there is no way to clear the previous functions from memory, as they are still running, waiting for the return of recursively called functions.

Eventually the stack will run out of space to allocate more data, occurring a stack overflow, or in English, stack overflow.

Else: 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.

  • Interesting. In my conception I always considered "overflow" being when a value exceeds the amount allowed in it and "reset" returning to the lowest value, as for example if you try to add 32767 + 1 in an int(short) variable. Thank you for the reply.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.