how to catch a “Maximum call stack size exceeded” error?

前端 未结 4 1236
走了就别回头了
走了就别回头了 2021-01-14 17:58
  try {
     requestAnimationFrame(function re(){
       re();
     })}
  catch (e){
       console.log(e);
     }

I tried above code in console, i

4条回答
  •  醉梦人生
    2021-01-14 18:06

    This can be certainly done. More than that – if you'll stick to a meaningful pattern, you can determine how many times your function had run before the call stack overflowed (I wouldn't dare to try it on a function that is recursively invoked, rather than returned, as in the original question, because in this case the call stack can get really funky):

    function doRecursionOrDieTryin(n = 0) {
        try {
        return doRecursionOrDieTryin(n + 1);
      } catch(err) {
        return `There was an exception: "${err}" when tryin' to make iteration no. ${n}`;
      }
    }
    
    doRecursionOrDieTryin()
    

    Warning: This function starts an infinite loop, so it could crash you browser if you will try to run this in a distant future, when the common JS engines will be fully tail-call-optimized. For 10/2018, it gots to iteration no. 10454 in Chrome 69. In Firefox 62 the limit of stack overfow is changing (from 10077 to 20989, then 22160), probably due to some kind of smart runtime optimization. Haven't test it yet in Edge.

提交回复
热议问题