Quick Answer
Resolve infinite recursion and stack overflow.
Understanding the Issue
This error occurs when the function call stack exceeds its limit, typically due to infinite recursion or excessively deep function nesting. Each function call adds to the stack until memory is exhausted.
The Problem
This code demonstrates the issue:
Javascript
Error
function infinite() {
infinite(); // Recurses forever
}
function deep(n) {
if (n <= 0) return;
deep(n - 1); // Too deep recursion
}
deep(100000);
The Solution
Here's the corrected code:
Javascript
Fixed
// Solution 1: Base case for recursion
function safeRecursion(n) {
if (n <= 0) return;
setTimeout(() => safeRecursion(n - 1), 0);
}
// Solution 2: Iterative approach
function iterative(n) {
while (n > 0) {
// Process here
n--;
}
}
// Solution 3: Trampoline pattern
function trampoline(fn) {
return (...args) => {
let result = fn(...args);
while (typeof result === 'function') {
result = result();
}
return result;
};
}
Key Takeaways
Prefer iterative solutions for deep recursion or use tail call optimization.