Превышен максимальный размер стека вызовов как исправить

Ситуация: заказчик попросил разместить на странице кликабельную картинку, а чтобы на неё обратило внимание больше посетителей, попросил сделать вокруг неё моргающую рамку. Логика моргания в скрипте очень простая:

  1. В первой функции находим на странице нужный элемент.
  2. Добавляем рамку с какой-то задержкой (чтобы она какое-то время была на экране).
  3. Вызываем функцию убирания рамки.
  4. Внутри второй функции находим тот же элемент на странице.
  5. Убираем рамку с задержкой.
  6. Вызываем первую функцию добавления рамки.

Код простой, поэтому делаем всё в одном файле:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Pulse</title>
	<style type="text/css">
	/*	рамка, которая будет моргать	*/
		.pulse { box-shadow: 0px 0px 4px 4px #AEA79F; }
	</style>
</head>
<body>
	<div id="pulseDiv"> 
    	<a href="#">
      		<div id="advisersDiv">
        		<img src="https://thecode.media/wp-content/uploads/2020/08/photo_2020-08-05-12.04.57.jpeg">
        	</div>
      	</a>
</div>
<!-- подключаем jQuery -->
<script src="https://yastatic.net/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<!-- наш скрипт -->
<script type="text/javascript">
	// добавляем рамку
	function fadeIn() {
		// находим нужный элемент и добавляем рамку с задержкой
  	$('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
  	// затем убираем рамку
  	fadeOut();
	};
	// убираем рамку
	function fadeOut() {
		// находим нужный элемент и убираем рамку с задержкой
   	$('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
   	// затем добавляем 
   	fadeIn();
	};
	// запускаем моргание рамки
	fadeIn();
</script>

</body>
</html>

Но при открытии страницы в браузере мы видим, что ничего не моргает, а в консоли появилась ошибка:

❌ Uncaught RangeError: Maximum call stack size exceeded

Что это значит: в браузере произошло переполнение стека вызовов и из-за этого он не может больше выполнять этот скрипт.

Переполнения стека простыми словами означает вот что:

  1. Когда компьютер что-то делает, он это делает последовательно — 1, 2, 3, 4.
  2. Иногда ему нужно отвлечься от одного и сходить сделать что-то другое — а, б, в, г, д. Получается что-то вроде 1, 2, 3 → а, б, в, г, д → 4.
  3. Вот эти переходы 3 → а и д → 4 — это компьютеру нужно запомнить, что он выполнял пункт 3, и потом к нему вернуться.
  4. Каждое запоминание, что компьютер бросил и куда ему нужно вернуться, — это называется «вызов».
  5. Вызовы хранятся в стеке вызовов. Это стопка таких ссылок типа «когда закончишь вот это, вернись туда».
  6. Стек не резиновый и может переполняться.

Что делать с ошибкой Uncaught RangeError: Maximum call stack size exceeded

Эта ошибка — классическая ошибка переполнения стека во время выполнения рекурсивных функций.

Рекурсия — это когда мы вызываем функцию внутри самой себя, но чуть с другими параметрами. Когда параметр дойдёт до конечного значения, цепочка разматывается обратно и функция собирает вместе все значения. Это удобно, когда у нас есть чёткий алгоритм подсчёта с понятными правилами вычислений.

В нашем случае рекурсия возникает, когда в конце обеих функций мы вызываем другую: 

  1. Функции начинают бесконтрольно вызывать себя бесконечное число раз.
  2. Стек вызовов начинает запоминать вызов каждой функции, чтобы, когда она закончится, вернуться к тому, что было раньше.
  3. Стек — это определённая область памяти, у которой есть свой объём.
  4. Вызовы не заканчиваются, и стек переполняется — в него больше нельзя записать вызов новой функции, чтобы потом вернуться обратно.
  5. Браузер видит всё это безобразие и останавливает скрипт.

То же самое будет, если мы попробуем запустить простую рекурсию слишком много раз:

Что означает ошибка Uncaught RangeError: Maximum call stack size exceeded

Как исправить ошибку Uncaught RangeError: Maximum call stack size exceeded

Самый простой способ исправить эту ошибку — контролировать количество рекурсивных вызовов, например проверять это значение на входе. Если это невозможно, то стоит подумать, как можно переделать алгоритм, чтобы обойтись без рекурсии.

В нашем случае проблема возникает из-за того, что мы вызывали вторые функции бесконтрольно, поэтому они множились без ограничений. Решение — ограничить вызов функции одной секундой — так они будут убираться из стека и переполнения не произойдёт:

<script type="text/javascript">
// добавляем рамку
function fadeIn() {
	// находим нужный элемент и добавляем рамку с задержкой
	$('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
	// через секунду убираем рамку
	setTimeout(fadeOut,1000)
};
// убираем рамку
function fadeOut() {
	// находим нужный элемент и убираем рамку с задержкой
 	$('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
 	// через секунду добавляем рамку
	setTimeout(fadeIn,1000)
};
// запускаем моргание рамки
fadeIn();
</script>

Что означает ошибка Uncaught RangeError: Maximum call stack size exceeded

Вёрстка:

Кирилл Климентьев

It means that somewhere in your code, you are calling a function which in turn calls another function and so forth, until you hit the call stack limit.

This is almost always because of a recursive function with a base case that isn’t being met.

Viewing the stack

Consider this code…

(function a() {
    a();
})();

Here is the stack after a handful of calls…

Web Inspector

As you can see, the call stack grows until it hits a limit: the browser hardcoded stack size or memory exhaustion.

In order to fix it, ensure that your recursive function has a base case which is able to be met…

(function a(x) {
    // The following condition 
    // is the base case.
    if ( ! x) {
        return;
    }
    a(--x);
})(10);

Community's user avatar

answered May 23, 2011 at 10:05

alex's user avatar

16

In my case, I was sending input elements instead of their values:

$.post( '',{ registerName: $('#registerName') } )

Instead of:

$.post( '',{ registerName: $('#registerName').val() } )

This froze my Chrome tab to a point it didn’t even show me the ‘Wait/Kill’ dialog for when the page became unresponsive…

answered Aug 13, 2016 at 23:55

FK-'s user avatar

FK-FK-

1,4421 gold badge10 silver badges17 bronze badges

7

You can sometimes get this if you accidentally import/embed the same JavaScript file twice, worth checking in your resources tab of the inspector.

double-beep's user avatar

double-beep

4,97617 gold badges32 silver badges41 bronze badges

answered Apr 23, 2012 at 1:58

lucygenik's user avatar

lucygeniklucygenik

1,6882 gold badges16 silver badges18 bronze badges

6

There is a recursive loop somewhere in your code (i.e. a function that eventually calls itself again and again until the stack is full).

Other browsers either have bigger stacks (so you get a timeout instead) or they swallow the error for some reason (maybe a badly placed try-catch).

Use the debugger to check the call stack when the error happens.

answered May 23, 2011 at 9:55

Aaron Digulla's user avatar

Aaron DigullaAaron Digulla

320k108 gold badges595 silver badges816 bronze badges

3

The problem with detecting stackoverflows is sometimes the stack trace will unwind and you won’t be able to see what’s actually going on.

I’ve found some of Chrome’s newer debugging tools useful for this.

Hit the Performance tab, make sure Javascript samples are enabled and you’ll get something like this.

It’s pretty obvious where the overflow is here! If you click on extendObject you’ll be able to actually see the exact line number in the code.

enter image description here

You can also see timings which may or may not be helpful or a red herring.

enter image description here


Another useful trick if you can’t actually find the problem is to put lots of console.log statements where you think the problem is. The previous step above can help you with this.

In Chrome if you repeatedly output identical data it will display it like this showing where the problem is more clearly. In this instance the stack hit 7152 frames before it finally crashed:

enter image description here

answered Mar 7, 2017 at 13:03

Simon_Weaver's user avatar

Simon_WeaverSimon_Weaver

138k81 gold badges639 silver badges680 bronze badges

1

In my case, I was converting a large byte array into a string using the following:

String.fromCharCode.apply(null, new Uint16Array(bytes))

bytes contained several million entries, which is too big to fit on the stack.

answered Mar 24, 2017 at 16:48

Nate Glenn's user avatar

Nate GlennNate Glenn

6,4358 gold badges49 silver badges95 bronze badges

6

In my case, click event was propagating on child element. So, I had to put the following:

e.stopPropagation()

on click event:

 $(document).on("click", ".remove-discount-button", function (e) {
           e.stopPropagation();
           //some code
        });
 $(document).on("click", ".current-code", function () {
     $('.remove-discount-button').trigger("click");
 });

Here is the html code:

 <div class="current-code">                                      
      <input type="submit" name="removediscountcouponcode" value="
title="Remove" class="remove-discount-button">
   </div>

Full Stack Alien's user avatar

answered Jan 16, 2017 at 15:36

Shahdat's user avatar

ShahdatShahdat

5,3034 gold badges37 silver badges37 bronze badges

This can also cause a Maximum call stack size exceeded error:

var items = [];
[].push.apply(items, new Array(1000000)); //Bad

Same here:

items.push(...new Array(1000000)); //Bad

From the Mozilla Docs:

But beware: in using apply this way, you run the risk of exceeding the
JavaScript engine’s argument length limit. The consequences of
applying a function with too many arguments (think more than tens of
thousands of arguments) vary across engines (JavaScriptCore has
hard-coded argument limit of 65536), because the limit (indeed even
the nature of any excessively-large-stack behavior) is unspecified.
Some engines will throw an exception. More perniciously, others will
arbitrarily limit the number of arguments actually passed to the
applied function. To illustrate this latter case: if such an engine
had a limit of four arguments (actual limits are of course
significantly higher), it would be as if the arguments 5, 6, 2, 3 had
been passed to apply in the examples above, rather than the full
array.

So try:

var items = [];
var newItems = new Array(1000000);
for(var i = 0; i < newItems.length; i++){
  items.push(newItems[i]);
}

answered Jun 28, 2019 at 15:45

bendytree's user avatar

bendytreebendytree

12.9k10 gold badges73 silver badges90 bronze badges

1

Check the error details in the Chrome dev toolbar console, this will give you the functions in the call stack, and guide you towards the recursion that’s causing the error.

answered May 28, 2012 at 8:48

chim's user avatar

chimchim

8,3633 gold badges51 silver badges60 bronze badges

0

In my case, I basically forget to get the value of input.

Wrong

let name=document.getElementById('name');
param={"name":name}

Correct

let name=document.getElementById('name').value;
param={"name":name}

answered Aug 24, 2020 at 7:50

Aman's user avatar

AmanAman

2,2263 gold badges17 silver badges22 bronze badges

2

In my case, it was that I have 2 variables with the same name!

answered Sep 8, 2021 at 1:26

Nandostyle's user avatar

NandostyleNandostyle

3142 silver badges12 bronze badges

Nearly every answer here states that this can only be caused by an infinite loop. That’s not true, you could otherwise over-run the stack through deeply nested calls (not to say that’s efficient, but it’s certainly in the realm of possible). If you have control of your JavaScript VM, you can adjust the stack size. For example:

node --stack-size=2000

See also: How can I increase the maximum call stack size in Node.js

answered Feb 6, 2019 at 20:48

hayesgm's user avatar

hayesgmhayesgm

8,6201 gold badge38 silver badges40 bronze badges

We recently added a field to an admin site we are working on — contact_type… easy right? Well, if you call the select «type» and try to send that through a jquery ajax call it fails with this error buried deep in jquery.js Don’t do this:

$.ajax({
    dataType: "json",
    type: "POST",
    url: "/some_function.php",
    data: { contact_uid:contact_uid, type:type }
});

The problem is that type:type — I believe it is us naming the argument «type» — having a value variable named type isn’t the problem. We changed this to:

$.ajax({
    dataType: "json",
    type: "POST",
    url: "/some_function.php",
    data: { contact_uid:contact_uid, contact_type:type }
});

And rewrote some_function.php accordingly — problem solved.

answered Apr 9, 2019 at 19:35

Scott's user avatar

ScottScott

6851 gold badge8 silver badges16 bronze badges

1

Sending input elements instead of their values will most likely resolve it like FK mentioned

answered Oct 17, 2021 at 10:08

El_boogy's user avatar

1

In my case, two jQuery modals were showing stacked on top of each other. Preventing that solved my problem.

answered Dec 28, 2016 at 21:23

Baz Guvenkaya's user avatar

Baz GuvenkayaBaz Guvenkaya

1,4823 gold badges17 silver badges26 bronze badges

Check if you have a function that calls itself. For example

export default class DateUtils {
  static now = (): Date => {
    return DateUtils.now()
  }
}

answered Nov 22, 2018 at 13:13

onmyway133's user avatar

onmyway133onmyway133

45.2k28 gold badges255 silver badges262 bronze badges

For me as a beginner in TypeScript, it was a problem in the getter and the setter of _var1.

class Point2{
    
    constructor(private _var1?: number, private y?: number){}

    set var1(num: number){
        this._var1 = num  // problem was here, it was this.var1 = num
    }
    get var1(){
        return this._var1 // this was return this.var1
    }
}

answered Aug 4, 2020 at 14:20

ReemRashwan's user avatar

ReemRashwanReemRashwan

3413 silver badges8 bronze badges

dtTable.dataTable({
    sDom: "<'row'<'col-sm-6'l><'col-sm-6'f>r>t<'row'<'col-sm-6'i><'col-sm-6'p>>",
    "processing": true,
    "serverSide": true,
    "order": [[6, "desc"]],
    "columnDefs": [
        {className: "text-right", "targets": [2, 3, 4, 5]}
    ],
    "ajax": {
        "url": "/dt",
        "data": function (d) {
            d.loanRef = loanRef;
        }
    },
    "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
        var editButton = '';
        // The number of columns to display in the datatable
        var cols = 8;
        // Th row element's ID
        var id = aData[(cols - 1)];
    }
});

In the data function above, I used the same name d.loanRef = loanRef but had not created a variable loanRef therefore recursively declaring itself.

Solution: Declare a loanRef variable or better still, use a different name from the one used on d.loanRef.

answered Mar 7, 2021 at 5:56

Kihats's user avatar

KihatsKihats

3,2565 gold badges29 silver badges46 bronze badges

Both invocations of the identical code below if decreased by 1 work in Chrome 32 on my computer e.g. 17905 vs 17904. If run as is they will produce the error «RangeError: Maximum call stack size exceeded». It appears to be this limit is not hardcoded but dependant on the hardware of your machine. It does appear that if invoked as a function this self-imposed limit is higher than if invoked as a method i.e. this particular code uses less memory when invoked as a function.

Invoked as a method:

var ninja = {
    chirp: function(n) {
        return n > 1 ? ninja.chirp(n-1) + "-chirp" : "chirp";
    }
};

ninja.chirp(17905);

Invoked as a function:

function chirp(n) {
    return n > 1 ? chirp( n - 1 ) + "-chirp" : "chirp";
}

chirp(20889);

answered Feb 20, 2014 at 13:12

Elijah Lynn's user avatar

Elijah LynnElijah Lynn

12.1k10 gold badges61 silver badges90 bronze badges

I also faced similar issue here is the details
when uploading logo using dropdown logo upload box

<div>
      <div class="uploader greyLogoBox" id="uploader" flex="64" onclick="$('#filePhoto').click()">
        <img id="imageBox" src="{{ $ctrl.companyLogoUrl }}" alt=""/>
        <input type="file" name="userprofile_picture"  id="filePhoto" ngf-select="$ctrl.createUploadLogoRequest()"/>
        <md-icon ng-if="!$ctrl.isLogoPresent" class="upload-icon" md-font-set="material-icons">cloud_upload</md-icon>
        <div ng-if="!$ctrl.isLogoPresent" class="text">Drag and drop a file here, or click to upload</div>
      </div>
      <script type="text/javascript">
          var imageLoader = document.getElementById('filePhoto');
          imageLoader.addEventListener('change', handleImage, false);

          function handleImage(e) {
              var reader = new FileReader();
              reader.onload = function (event) {

                  $('.uploader img').attr('src',event.target.result);
              }
              reader.readAsDataURL(e.target.files[0]);
          }
      </script>
      </div>

CSS.css

.uploader {
  position:relative;
  overflow:hidden;
  height:100px;
  max-width: 75%;
  margin: auto;
  text-align: center;

  img{
    max-width: 464px;
    max-height: 100px;
    z-index:1;
    border:none;
  }

  .drag-drop-zone {
    background: rgba(0, 0, 0, 0.04);
    border: 1px solid rgba(0, 0, 0, 0.12);
    padding: 32px;
  }
}

.uploader img{
  max-width: 464px;
  max-height: 100px;
  z-index:1;
  border:none;
}



.greyLogoBox {
  width: 100%;
  background: #EBEBEB;
  border: 1px solid #D7D7D7;
  text-align: center;
  height: 100px;
  padding-top: 22px;
  box-sizing: border-box;
}


#filePhoto{
  position:absolute;
  width:464px;
  height:100px;
  left:0;
  top:0;
  z-index:2;
  opacity:0;
  cursor:pointer;
}

before correction my code was :

function handleImage(e) {
              var reader = new FileReader();
              reader.onload = function (event) {
                  onclick="$('#filePhoto').click()"
                  $('.uploader img').attr('src',event.target.result);
              }
              reader.readAsDataURL(e.target.files[0]);
          }

The error in console:

enter image description here

I solved it by removing onclick="$('#filePhoto').click()" from div tag.

answered Aug 3, 2017 at 8:37

spacedev's user avatar

spacedevspacedev

1,05613 silver badges13 bronze badges

2

I was facing same issue
I have resolved it by removing a field name which was used twice on ajax
e.g

    jQuery.ajax({
    url : '/search-result',
    data : {
      searchField : searchField,
      searchFieldValue : searchField,
      nid    :  nid,
      indexName : indexName,
      indexType : indexType
    },
.....

answered Nov 8, 2017 at 7:57

Tajdar Khan Afridi's user avatar

The issue in my case is because I have children route with same path with the parent :

const routes: Routes = [
  {
    path: '',
    component: HomeComponent,
    children: [
      { path: '', redirectTo: 'home', pathMatch: 'prefix' },
      { path: 'home', loadChildren: './home.module#HomeModule' },
    ]
  }
];

So I had to remove the line of the children route

const routes: Routes = [
  {
    path: '',
    component: HomeComponent,
    children: [
      { path: 'home', loadChildren: './home.module#HomeModule' },
    ]
  }
];

answered Jul 25, 2018 at 17:06

Amine Harbaoui's user avatar

Amine HarbaouiAmine Harbaoui

1,2372 gold badges16 silver badges33 bronze badges

1

The issue might be because of recursive calls without any base condition for it to terminate.

Like in my case, if you see the below code, I had the same name for the API call method and the method which I used to perform operations post that API call.

const getData = async () => {
try {
  const response = await getData(props.convID);
  console.log("response", response);
 } catch (err) {
  console.log("****Error****", err);
}
};

So, basically, the solution is to remove this recursive call.

answered May 16, 2022 at 15:03

Akshay Chavan's user avatar

you can find your recursive function in crome browser,press ctrl+shift+j and then source tab, which gives you code compilation flow and you can find using break point in code.

answered Mar 12, 2014 at 8:01

Vishal Patel's user avatar

1

I know this thread is old, but i think it’s worth mentioning the scenario i found this problem so it can help others.

Suppose you have nested elements like this:

<a href="#" id="profile-avatar-picker">
    <span class="fa fa-camera fa-2x"></span>
    <input id="avatar-file" name="avatar-file" type="file" style="display: none;" />
</a>

You cannot manipulate the child element events inside the event of its parent because it propagates to itself, making recursive calls until the exception is throwed.

So this code will fail:

$('#profile-avatar-picker').on('click', (e) => {
    e.preventDefault();

    $('#profilePictureFile').trigger("click");
});

You have two options to avoid this:

  • Move the child to the outside of the parent.
  • Apply stopPropagation function to the child element.

answered Jan 4, 2018 at 14:22

Weslley Ramos's user avatar

I had this error because I had two JS Functions with the same name

answered Jan 5, 2018 at 12:33

Monir Tarabishi's user avatar

Monir TarabishiMonir Tarabishi

7061 gold badge16 silver badges30 bronze badges

If you are working with google maps, then check if the lat lng are being passed into new google.maps.LatLng are of a proper format. In my case they were being passed as undefined.

answered Jan 30, 2018 at 13:25

User-8017771's user avatar

User-8017771User-8017771

1,4421 gold badge11 silver badges17 bronze badges

Sometimes happened because of convert data type , for example you have an object that you considered as string.

socket.id in nodejs either in js client as example, is not a string. to use it as string you have to add the word String before:

String(socket.id);

answered Jun 27, 2018 at 21:34

Hussein mahyoub's user avatar

in my case I m getting this error on ajax call and the data I tried to pass that variable haven’t defined, that is showing me this error but not describing that variable not defined. I added defined that variable n got value.

answered Aug 29, 2018 at 4:08

asifaftab87's user avatar

asifaftab87asifaftab87

1,28524 silver badges28 bronze badges

1

Here it fails at Array.apply(null, new Array(1000000)) and not the .map call.

All functions arguments must fit on callstack(at least pointers of each argument), so in this they are too many arguments for the callstack.

You need to the understand what is call stack.

Stack is a LIFO data structure, which is like an array that only supports push and pop methods.

Let me explain how it works by a simple example:

function a(var1, var2) {
    var3 = 3;
    b(5, 6);
    c(var1, var2);
}
function b(var5, var6) {
    c(7, 8);
}
function c(var7, var8) {
}

When here function a is called, it will call b and c. When b and c are called, the local variables of a are not accessible there because of scoping roles of Javascript, but the Javascript engine must remember the local variables and arguments, so it will push them into the callstack. Let’s say you are implementing a JavaScript engine with the Javascript language like Narcissus.

We implement the callStack as array:

var callStack = [];

Everytime a function called we push the local variables into the stack:

callStack.push(currentLocalVaraibles);

Once the function call is finished(like in a, we have called b, b is finished executing and we must return to a), we get back the local variables by poping the stack:

currentLocalVaraibles = callStack.pop();

So when in a we want to call c again, push the local variables in the stack. Now as you know, compilers to be efficient define some limits. Here when you are doing Array.apply(null, new Array(1000000)), your currentLocalVariables object will be huge because it will have 1000000 variables inside. Since .apply will pass each of the given array element as an argument to the function. Once pushed to the call stack this will exceed the memory limit of call stack and it will throw that error.

Same error happens on infinite recursion(function a() { a() }) as too many times, stuff has been pushed to the call stack.

Note that I’m not a compiler engineer and this is just a simplified representation of what’s going on. It really is more complex than this. Generally what is pushed to callstack is called stack frame which contains the arguments, local variables and the function address.

The JavaScript RangeError: Maximum call stack size exceeded is an error that occurs when there are too many function calls, or if a function is missing a base case.

Error message:

RangeError: Maximum call stack size exceeded

Error Type:

RangeError

What Causes RangeError: Maximum Call Stack Size Exceeded

The RangeError: Maximum call stack size exceeded is thrown when a function call is made that exceeds the call stack size. This can occur due to the following reasons:

  • Too many function calls.
  • Issues in handling recursion, e.g. missing base case in a recursive function to stop calling itself infinitely.
  • Out of range operations.

RangeError: Maximum Call Stack Size Exceeded Example

Here’s an example of a JavaScript RangeError: Maximum call stack size exceeded thrown when using a recursive function that does not have a base case:

function myFunc() {
    myFunc();
}

myFunc();

Since the recursive function myFunc() does not have a terminating condition (base case), calling it creates an infinite loop as the function keeps calling itself over and over again until the RangeError: Maximum call stack size exceeded error occurs:

Uncaught RangeError: Maximum call stack size exceeded
    at myFunc (test.js:2:2)
    at myFunc (test.js:2:2)
    at myFunc (test.js:2:2)
    at myFunc (test.js:2:2)
    at myFunc (test.js:2:2)
    at myFunc (test.js:2:2)
    at myFunc (test.js:2:2)
    at myFunc (test.js:2:2)
    at myFunc (test.js:2:2)
    at myFunc (test.js:2:2)

How to Avoid RangeError: Maximum Call Stack Size Exceeded

If this error is encountered when calling recursive functions, it should be ensured that the function has a defined base case to terminate the recursive calls.

In case this error occurs due to an excessive number of function calls or variables, these should be reduced as much as possible. Any out of range operations should also be checked and avoided. These issues can be inspected using the browser console and developer tools.

The earlier example can be updated to include a base case:

function myFunc(i) {
    if (i >= 5) {
        return;
    }
    myFunc(i+1);
}

myFunc(1);

The above code avoids the error since recursive calls terminate when the base case is met.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing JavaScript errors easier than ever. Sign Up Today!

Время на прочтение
6 мин

Количество просмотров 20K

Привет, Хабровчане!

Большинство разработчиков, которые использовали рекурсию для решения своих задач, видели такую ошибку:

 RangeError: Maximum call stack size exceeded. 

Но не каждый разработчик задумывался о том, а что означает «размер стэка вызовов» и каков же этот размер? А в чем его измерять?

Думаю, те, кто работают с языками, напрямую работающими с памятью, смогут легко ответить на этот вопрос, а вот типичный фронтэнд разработчик скорее всего задает себе подобные вопросы впервые. Что-ж, попробуем разобраться!

Многие полагают, что браузер ограничивает нас именно в количестве вызовов, но это не так. В данной статье я покажу на простых примерах, как это работает на самом деле.

О чем ты вообще, автор?

Для статьи важно понимание таких понятий как Execution Stack, Execution Context. Если вы не знаете, что это такое, то советую об этом почитать. На данном ресурсе уже было достаточно хороших статей на эту тему. Пример — https://habr.com/ru/company/ruvds/blog/422089/

Когда возникает эта ошибка?

Разберем на простом примере — функция, которая рекурсивно вызывает сама себя.

const func = () => {
    func();
}

Если попытаться вызвать такую функцию, то мы увидим в консоли/терминале ошибку, о которой я упомянул выше.

А что если подглядеть, сколько же раз выполнилась функция перед тем, как возникла ошибка?

На данном этапе код запускается в Chrome DevTools последней версии на март 2021. Результат будет различаться в разных браузерах. В дальнейшем в статье я упомяну об этом.

Для эксперимента будем использовать вот такой код:

let i = 0;

const func = () => {
  i++;

  func();
};

try {
  func();
} catch (e) {
  // Словили ошибку переполнения стэка и вывели значение счетчика в консоль
  console.log(i);
}

Результатом вывода в консоль стало число в 13914. Делаем вывод, что перед тем, как переполнить стэк, наша функция вызвалась почти 14 тысяч раз.

Магия начинается тогда, когда мы начинаем играться с этим кодом. Допустим, изменим его вот таким образом:

let i = 0;

const func = () => {
  let someVariable = i + 1;
  i++;

  func();
};

try {
  func();
} catch (e) {
  console.log(i);
}

Единственное, что мы добавили, это объявление переменной someVariable в теле функции. Казалось бы, ничего не поменялось, но число стало меньше. На этот раз функция выполнилась 12523 раз. Что более чем на тысячу меньше, чем в прошлом примере. Чтобы убедиться, что это не погрешность, пробуем выполнять такой код несколько раз, но видим одни и те же результаты в консоли.

Почему же так? Что изменилось? Как понять, посмотрев на функцию, сколько раз она может выполниться рекурсивно?!

Магия раскрыта

Отличие второго примера от первого — наличие дополнительной переменной внутри тела функции. На этом все. Соответственно, можно догадаться, именно из-за этого максимальное количество рекурсивных вызовов стало меньше. Что-ж, а что, если у нас будет не одна, а четыре переменных внутри функции? По этой логике, количество рекурсивных вызовов станет еще меньше? Проверим: 

let i = 0;

const func = () => {
  let a = i + 1;
  let b = a + 1;
  let c = b + 1;
  let d = c + 1;
  let e = d + 1;
  i++;

  func();
};

try {
  func();
} catch (e) {
  console.log(i);
}

По этой логике, значение счетчика должно стать еще меньше. Выдыхая, видим вывод — 8945. Ага, оно стало еще меньше. Значит, мы на правильном пути. Хочу привести небольшую аналогию, чтобы даже самым маленьким стало понятно.

Execution Stack (Call Stack) — это емкость с водой. Изначально она пустая. Так получилось, что эта емкость с водой стоит прямо на электрической проводке. Как только емкость переполнится, вода проливается на провода, и мы видим ошибку в консоли. При каждом новом рекурсивном вызове функции в стэк падает капелька воды. Само собой, чем капелька воды крупнее, тем быстрее наполнится стэк.

Емкости бывают разные по размеру. И размер емкости в данном примере — это размер коллстэка. А точнее — количество байт, которое он максимально может в себе удержать. Как гласит статья про Call Stack (Execution Stack), которую я приложил в начале, на каждый вызов функции создается Execution Context — контекст вызова функции (не путать с this). И упрощая, в нем, помимо разных «подкапотных» штук, содержатся все переменные, которые мы объявили внутри функции. Как Execution Context, так и каждая переменная внутри него имеют определенный размер, который они занимают в памяти. Сложив эти два размера мы и получим «размер» капли, которая капает в кувшин при каждом рекурсивном вызове функции.

У нас уже достаточно много данных. Может быть, поэкспериментируем еще? А давайте попробуем вычислить, какой размер коллстэка в движке, который использует Chrome?

Математика все-таки пригодилась

Как мы выяснили, у нас есть две неизвестные, которые составляют размер функции (капельки, которая падает в емкость). Это размер самого Execution Stack, а так же сумма размеров всех переменных внутри функции. Назовем первую N, а вторую K. Сам же неизвестный размер коллстэка обозначим как X.

В итоге — количество байт, которое занимает функция (в упрощенном виде) будет:

FunctionSize = N + K * SizeOfVar

SizeOfVar в данном случае — количество байт, которые занимает переменная в памяти.

Учитывая, что мы знаем количество вызовов первой функции, в теле которой не объявляются переменные, размер коллстэка можно выразить как:

X = (N + 0 *  SizeOfVar)* 13914 = N * 13914

И, для второго случая, возьмем функцию, внутри которой было объявлено пять переменных.

X = (N + 5 * SizeOfVar) * 8945

Иксы в обоих случаях обозначают одно и то же число — размер коллстэка. Как учили в школе, можем приравнять правые части уравнений.

N * 13914 = (N + 5 * SizeOfVar) * 8945

Выглядит неплохо. У нас тут две неизвестные переменные — N и SizeOfVar. Если N мы не можем откуда-то узнать, то что насчет SizeOfVar? Заметим, что во всех функциях, которые фигурировали выше, переменные хранили значение с типом «number», а значит, нужно просто узнать, сколько же байт в памяти занимает одна такая переменная.

С помощью великого гугла получаем ответ — «Числа в JavaScript представлены 64-битными значениями с плавающей запятой. В байте 8 бит, в результате каждое число занимает 64/8 = 8 байт.» Вот она — последняя неизвестная. 8 байт. Подставляем ее в наше уравнение и считаем, чем равно N.

N * 13914 = (N + 5 * 8) * 8945

Упрощаем:

N * 13914 = N * 8945 + 40 * 8945

Если выразить отсюда N, то получим ответ: N равно приблизительно 72. В данном случае 72 байтам.

Теперь, подставив N = 72 в самое первое уравнение, получим, что размер коллстэка в Chrome равен… 1002128 байтов. Это почти один мегабайт. Не так уж и много, согласитесь.

Мы получили какое-то число, но как убедиться, что наши расчеты верны и число правильное? А давайте попробуем с помощью этого числа спрогнозировать, сколько раз сможет выполниться функция, внутри которой будет объявлено 7 переменных типа ‘number’. 

Считаем: Ага, каждая функция будет занимать (72 + 7 * 8) байт, это 128. Разделим 1002128 на 128 и получим число… 7829! Согласно нашим расчетам, такая функция сможет рекурсивно вызваться именно 7829 раз! Идем проверять это в реальном бою…

Мы были очень даже близки. Реальное число отличается от теоретического всего на 3. Я считаю, что это успех. В наших расчетах было несколько округлений, поэтому результат мы посчитали не идеально, но, очень-очень близко. Небольшая погрешность в таком деле — нормально.

Получается, что мы посчитали все верно и можем утверждать, что размер пустого ExecutionStack в Chrome равен 72 байтам, а размер коллстэка — чуть меньше одного мегабайта.

Отличная работа!

Важное примечание

Размер стэка разнится от браузера к браузеру. Возьмем простейшую функцию из начала статьи. Выполнив ее в Сафари получим совершенно другую цифру. Целых 45606 вызовов. Функция с пятью переменными внутри выполнилась бы 39905 раз. В NodeJS числа очень близки к Chrome по понятным причинам. Любопытный читатель может проверить это самостоятельно на своем любимом движке JavaScript. 

А что с непримитивами?

Если с числами все вроде бы понятно, то что насчет типа данных Object? 

let i = 0;

const func = () => {
  const a = {
    key: i + 1,
  };
  i++;

  func();
};

try {
  func();
} catch (e) {
  console.log(i);
}

Простейший пример на ваших глазах. Такая функция сможет рекурсивно вызваться 12516. Это практически столько же, сколько и функция с одной переменной внутри. Тут в дело вступает механизм хранения и передачи объектов в JS’е — по ссылке. Думаю, большинство уже знают об этом.

А что с этим? А как поведет себя вот это? А что с *?

Как вы заметили, экспериментировать можно бесконечно. Можно придумать огромное количество кейсов, которые будут прояснять эту ситуацию глубже и глубже. Можно ставить эксперименты при разных условиях, в разных браузерах, на разных движках. Оставляю это на тех, кого эта тема заинтересовала.

Итоги:

  • Количество рекурсивных вызовов функции до переполнения стэка зависит от самих функций.

  • Размер стэка измеряется в байтах.

  • Чем «тяжелее» функция, тем меньше раз она может быть вызвана рекурсивно.

  • Размер стэка в разных движках различается.

Вопрос особо любознательным: А сколько переменных типа «number» должно быть объявлено в функции, чтобы она могла выполниться рекурсивно всего два раза, после чего стэк переполнится?

Понравилась статья? Поделить с друзьями:
  • Как составить ходатайство мировому судье
  • Как составить древо своей семьи пример
  • Как исправить швы плитки в ванной
  • Как найти сохранения walking dead
  • Как найти силу тяги через коэффициент сопротивления