console.log避免最大调用堆栈

Tim*_*Lee 4 javascript v8 node.js

下面的代码出现Maximum call stack size exceeded了预期的错误。

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

recurrent ()
Run Code Online (Sandbox Code Playgroud)

我希望这也超过了最大调用堆栈数。但是,它为什么运行?

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

recurrent ()
Run Code Online (Sandbox Code Playgroud)

结果:

打印到一个数字并停止,但没有错误。

...
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
Run Code Online (Sandbox Code Playgroud)

我在Windows 10上使用NodeJs 10

更新资料

Chrome出现错误 在此处输入图片说明

ajx*_*jxs 5

他们都会以完全相同的方式失败,就像人们期望的那样。只是log语句将功能减慢到可能不会立即失败的程度。

以下是使用time以下命令计时每个版本的结果:

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

real    0m0.204s
user    0m0.171s
sys 0m0.035s
Run Code Online (Sandbox Code Playgroud)
# Without logging
...
RangeError: Maximum call stack size exceeded

real    0m0.082s
user    0m0.054s
sys 0m0.021s
Run Code Online (Sandbox Code Playgroud)

在Chrome中进行测试时,会发生相同的过程,但是速度要慢得多。RangeError投掷了超过30秒的时间。