The Maximum call stack size exceeded the Maximum call value.

  • The maximum call stack size
  • Translator: Fundebug

To ensure readability, free translation rather than literal translation is used in this paper. In addition, the copyright of this article belongs to the original author, and translation is for study only.

Uncaught RangeError: Maximum Call Stack Size exceeded if you write an Uncaught RangeError: Maximum call stack size exceeded if you write an Uncaught RangeError: Maximum call Stack size exceeded So what is the call stack size?

1. Calculation method

The following method will help you figure out how deep your JavaScript engine can support (inspired by a piece of code by Ben Alman) :

function computeMaxCallStackSize() {
        try {
            return 1 + computeMaxCallStackSize();
        } catch (e) {
            // Call stack overflow
            return 1; }}Copy the code

The results are as follows:

  • Node.js: 11034
  • Firefox: 50994
  • Chrome: 10402

What do these numbers mean? Mr.Aleph told me that in V8, the number of callable layers is based on two aspects: 1. Stack size; 2. The size of each stack frame (used to record function parameters and local variables). You can test this by declaring local variables at computeMaxCallStackSize, and you’ll see that the numbers get smaller.

2. Tail-recursive optimization in ECMAScript 6

ECMAScript 6 supports tail-recursive optimization: if the last operation of a function is a function call, “jump” will be used instead of “child call”. That is, if you rewrite computeMaxCallStackSize as follows, it will always run in ES6’s strict mode.

 function computeMaxCallStackSize(size) {
        size = size || 1;
        return computeMaxCallStackSize(size + 1);
    }
Copy the code

3. Highlight reviews

  • Andrei: The “ECMAScript 6” version doesn’t work at all. Size is changed, but no value is returned.
  • Andrei: Interesting! You can’t use this code to calculate stack size. Under ES6, this code runs forever, so it does not return data. In other cases, RangeError is returned. To make it work, I rewrote the code:
var computeMaxCallStackSize = (function() {
  return function() {
    var size = 0;
    function cs() {
      try {
        size++;
        return cs();
      } catch(e) {
        return size + 1; }}returncs(); }; } ());Copy the code

About Fundebug

Fundebug focuses on BUG monitoring of JavaScript, wechat mini programs and small games. Since its official launch on November 11, 2016, Fundebug has been serving for one and a half years and has handled over 500 million error events in total, which has been recognized by many well-known users. Fundebug supports mainstream front-end framework bug monitoring, welcome to experience!