Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

console.log avoid maximum call stack

Code below got error Maximum call stack size exceeded as expected.

function recurrent (i = 0) {
  recurrent(++i)
}

recurrent ()

I expect this exceeded the maximum call stack, too. However, it runs, why?

function recurrent (i = 0) {
  console.log(i)
  recurrent(++i)
}

recurrent ()

Result:

print till a number and stop, but no errors.

...
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824

I'm using NodeJs 10 on Windows 10

Update

Chrome got error enter image description here

like image 363
Timothy Lee Avatar asked Aug 06 '19 02:08

Timothy Lee


People also ask

How can we avoid maximum call stack size exceeded?

The call stack is limited in size, and when it's exceeded, the RangeError is thrown. This can happen when a deeply nested function is called, or when a lot of new variables are created. The most common way to fix this error is to reduce the number of function calls, or to limit the number of variables that are created.

Does console log go on call stack?

log() is, externally, a simple function call. What happens inside the console implementation is up to the runtime. It's a function call. It goes to the call stack.

How do I fix maximum call stack size exceeded see JavaScript console for details?

Sometimes you get Maximum call stack size exceeded error if you accidentally import/embed the same JavaScript file twice. So its worth checking in your resources tab of the inspector to solve this issue.

What does error RangeError maximum call stack size exceeded see JavaScript console for details mean?

The "RangeError: Maximum call stack size exceeded" error occurs when a function is called so many times that the invocations exceed the call stack limit. To solve the error, specify a base case that has to be met to exit the recursion.


Video Answer


1 Answers

They'll both fail in the exact same way, as one would expect. It's just that the log statement slows the function down to a degree that it may not appear to fail immediately.

Here's the results of timing each version using time:

# With logging:
...
RangeError: Maximum call stack size exceeded

real    0m0.204s
user    0m0.171s
sys 0m0.035s
# Without logging
...
RangeError: Maximum call stack size exceeded

real    0m0.082s
user    0m0.054s
sys 0m0.021s

When testing this in Chrome the same process occurs, however much, much slower. It took over 30 seconds before the RangeError was thrown.

like image 135
ajxs Avatar answered Oct 19 '22 03:10

ajxs