ChatGPT解决这个技术问题 Extra ChatGPT

Maximum call stack size exceeded error

I am using a Direct Web Remoting (DWR) JavaScript library file and am getting an error only in Safari (desktop and iPad)

It says

Maximum call stack size exceeded.

What exactly does this error mean and does it stop processing completely?

Also any fix for Safari browser (Actually on the iPad Safari, it says

JS:execution exceeded timeout

which I am assuming is the same call stack issue)

i got this error when trying to send variables (without declaring them), through data in ajax. Fixed the error by declaring the variables.
infinite loop ...
For me, the name of my JavaScript function was onclick() and I got this error :-) While these are reserved names

C
Community

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...

https://i.stack.imgur.com/aSwnu.png

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);

Thx a lot for that..So is there any way/tool by which I can that the stack limit is being exhausted..Again, as this is a huge library file and not created by me, I am not completely aware as to where things might be going wrong..
@Oliver If you have to run a function nearly 300 trillion times, you're probably doing something wrong.
@Oliver - you might want to look into dynamic programming - my guess is you don't have that many unique solutions, you're repeating steps, so you may need to program it to be polynumial time rather than quadratic. en.wikipedia.org/wiki/Dynamic_programming
@Akhoy In a regular function yes, but think about a recursive function. It calls another (itself) and leaves the return address of the former on the stack (otherwise where would the PC know where to go?) This of course calls itself again, each time pushing a return address onto the stack. When this runs away due to a base case that isn't likely to be met in the next century, you get a stack overflow.
Your code runs that same inefficient segment 134217728 times. No kidding its slow. You should use bitwise operators so you can unroll the 9 levels of loops into one level of loops.
d
double-beep

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


This problem usually happens when you accidentally import/embed the same JS file twice. The exact process that causes the recursive loop is not something I care to speculate on, however I would assume it is something like driving two identical cars at 100mph through the same toll gateway.
I don't think this is the case. If two same kind of functions or variables are embedded, the latter will override the previous definitions.
Yeah... I don't really know why it happens or what the process is, I would have though it would override too.
Little bit late to the party, but would imagine that it's when code is outside of any function, both would be executed within the two JS files, and one would probably not overwrite eachother as they are outside of any function.
@lucygenik next time you want to be more careful when approving troll edits on your posts. This post almost got deleted as spam (check history)
F
FK-

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...


I wonder why there is not an exception for such error... Thanks!
Thanks a lot, this saved me
I was about to add this as a possible solution. I just did this exact thing lol
"I wonder why there is not an exception for such error..." because it is javascript.
Thank you. This was the problem
A
Aaron Digulla

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.


Thx a lot for your reply. On IE/FF, the code seems to run fine..Only in desktop Safari and iPad Safari, I get the error. Actually the JS file is not my own creation, but is a library file (from DWR engine.js)..directwebremoting.org Also when you say "debugger to check the call stack ", how do I do that using the Safari Inspector?
I have no experience with Safari Inspector. Try to open the JavaScript debugger and load your page. The debugger should stop when an uncatched error is thrown. If that doesn't work, ask on superuser or webmasters (see bottom of the page)
had 2 functions named the same thing!! DOH!
S
Simon_Weaver

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.

https://i.stack.imgur.com/qtrDa.png

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

https://i.stack.imgur.com/sGnvq.png

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:

https://i.stack.imgur.com/8wVYn.png


For anyone reading this answer. Of course it worked for me and I was able to narrow it down to a recursive function call. I was easily able to trace the problem right away with the Performance tab. It was due to 2 angular elements assets being included in a separate app. Once I disabled one of the elements, the problem disappeared. Hope this helps someone!
N
Nate Glenn

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.


I too had same problem with the same line!! thanx
so what is the best solution for converting large byte array??
@KarthikHande You have to do it in a for loop instead of in one call. var uintArray = new Uint16Array(bytes); var converted = []; uintArray.forEach(function(byte) {converted.push(String.fromCharCode(byte))});
how do I convert that to JSON?I tried JSON.parse but it didn't work...I'm using Uintl8Array
@KarthikHande I can't tell without seeing the whole problem. Please open another question with all of the details.
V
Vim Diesel

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>

b
bendytree

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]);
}

this is very bad practice when inserting nodes into the dom, however you may be right...doing el.append(...divs) after the loop causes this error if you have enough nodes.
c
chim

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.


N
Nandostyle

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


D
Dr. Dama

If you need a infinite process/recursion running for some reason, you can use a webworker in a seperate thread. http://www.html5rocks.com/en/tutorials/workers/basics/

if you want to manipulate dom elements and redraw, use animation http://creativejs.com/resources/requestanimationframe/


h
hayesgm

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


S
Scott

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.


Thanks for writing this answer. Actually, I found that I did not create the variable which I was Posting to the server-side script.
A
Aman

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}

It is similar to @FKasa , this is in javascript
Exactly what happened to me - I've accidently send the whole input field, not just the value of the field.
E
El_boogy

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


B
Baz Guvenkaya

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


o
onmyway133

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

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

R
ReemRashwan

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
    }
}

K
Kihats
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.


E
Elijah Lynn

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);

s
spacedev

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:

https://i.stack.imgur.com/ZbGVS.png

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


Where did you add the click()
I wanted to answer but system suggested to gaze through old ones first. Yes, I also had this onclick="$obj.click()"in my HTML. Looks like it loops jquery attachment in some way
T
Tajdar Khan Afridi

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
    },
.....

A
Amine Harbaoui

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' },
    ]
  }
];

Yep. I got it solved with this one. I had a recursion in the Angular 11 routes
V
Vishal Patel

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.


Sometimes however, it can be hard to figure out where the error originated. We have a LOT of JavaScript on our site.
W
Weslley Ramos

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.


M
Monir Tarabishi

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


U
User-8017771

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.


H
Hussein mahyoub

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);

a
asifaftab87

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.


got burned in a similar manner myself, in my case it was because I typoed a variable name...effectively the same thing.
P
Phillip Quinlan

I was trying to assign a variable, a value, when that variable had not been declared.

Declaring the variable fixed my error.