The most-common cause of stack overflow is excessively deep or infinite recursion, in which a function calls itself so many times that the space needed to store the variables and information associated with each call is more than can fit on the stack.
In order to prevent stack overflow bugs, you must have a base case where the function stops make new recursive calls. If there is no base case then the function calls will never stop and eventually a stack overflow will occur. Here is an example of a recursive function with a base case.
In imperative programming languages, recursive functions should be avoided in most cases (please, no hate mail about how this isn't true 100% of the time). Recursive functions are less efficient than their iterative counterparts. Additionally, they are subject to the perils of stack overflows.
If a recursion never reaches a base case, it will go on making recursive calls forever and the program will never terminate. This is known as infinite recursion, and it is generally not considered a good idea. In most programming environments, a program with an infinite recursion will not really run forever.
I'm failing to figure out why calling recSetTimeOut()
does not result in a stack overflow error, while recPromise()
does.
const recSetTimeOut = () => {
console.log('in recSetTimeOut');
setTimeout(recSetTimeOut, 0)
};
recSetTimeOut();
const recPromise = () => {
console.log('in recPromise');
Promise.resolve().then(recPromise);
}
recPromise();
Why does it happen? What is the difference between them?
Can you explain the process behind the scene?
Edit with a bit more of information
Running this snippets on Node.js v12.1.0
and Chrome DevTools
:
const recSetTimeOut = () => { setTimeout(recSetTimeOut, 0); }
recSetTimeOut();
Result Node
: No error.
Result Chrome
: No error.
const recPromise = () => { Promise.resolve().then(recPromise); }
recPromise();
Result Node
:
FATAL ERROR: invalid table size Allocation failed - JavaScript heap out of memory
Result Chrome
: Browser crushes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With