753

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)

3
  • 4
    i got this error when trying to send variables (without declaring them), through data in ajax. Fixed the error by declaring the variables.
    – phpfresher
    Jan 4, 2019 at 13:48
  • infinite loop ...
    – mercury
    Jul 5, 2021 at 5:20
  • For me, the name of my JavaScript function was onclick() and I got this error :-) While these are reserved names
    – sbr
    Jan 24, 2022 at 7:49

39 Answers 39

831

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);
16
  • 7
    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.. May 23, 2011 at 10:08
  • 91
    @Oliver If you have to run a function nearly 300 trillion times, you're probably doing something wrong.
    – ceejayoz
    Dec 30, 2014 at 21:07
  • 4
    @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
    – newshorts
    May 24, 2015 at 21:04
  • 5
    @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.
    – alex
    Jan 19, 2016 at 12:56
  • 5
    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.
    – Jack G
    Mar 29, 2017 at 22:54
113

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

8
  • 5
    I wonder why there is not an exception for such error... Thanks!
    – Džuris
    Nov 26, 2018 at 10:57
  • 1
    Thanks a lot, this saved me
    – Eme Hado
    Dec 4, 2019 at 13:16
  • I was about to add this as a possible solution. I just did this exact thing lol
    – mbuchok
    Apr 10, 2020 at 18:48
  • "I wonder why there is not an exception for such error..." because it is javascript.
    – GGesheva
    Apr 23, 2021 at 11:19
  • Thank you. This was the problem Jun 30, 2021 at 14:48
104

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

6
  • 9
    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.
    – lucygenik
    Jun 22, 2014 at 21:03
  • 4
    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.
    – ssudaraka
    Oct 27, 2017 at 9:48
  • Yeah... I don't really know why it happens or what the process is, I would have though it would override too.
    – lucygenik
    Oct 29, 2017 at 20:12
  • 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. May 14, 2018 at 7:03
  • 1
    @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) May 5, 2019 at 9:37
37

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.

3
  • 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? May 23, 2011 at 9:58
  • 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) May 23, 2011 at 11:53
  • had 2 functions named the same thing!! DOH! Jun 2, 2014 at 18:10
32

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

1
  • 1
    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!
    – Saturn K
    Jan 24, 2021 at 22:48
21

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.

6
  • I too had same problem with the same line!! thanx
    – ksh
    Jul 5, 2017 at 11:14
  • so what is the best solution for converting large byte array??
    – ksh
    Jul 5, 2017 at 11:14
  • 11
    @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))});
    – Nate Glenn
    Jul 6, 2017 at 5:41
  • how do I convert that to JSON?I tried JSON.parse but it didn't work...I'm using Uintl8Array
    – ksh
    Jul 6, 2017 at 13:07
  • @KarthikHande I can't tell without seeing the whole problem. Please open another question with all of the details.
    – Nate Glenn
    Jul 7, 2017 at 9:44
12

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]);
}
1
  • 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.
    – chovy
    May 7, 2022 at 10:55
8

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

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

5

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.

0
5

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}
2
  • It is similar to @FKasa , this is in javascript
    – Aman
    Aug 24, 2020 at 7:51
  • 1
    Exactly what happened to me - I've accidently send the whole input field, not just the value of the field.
    – FrenkyB
    Feb 4, 2022 at 11:44
4

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/

4

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

4

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.

1
  • 1
    Thanks for writing this answer. Actually, I found that I did not create the variable which I was Posting to the server-side script. Jul 11, 2021 at 10:10
4

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

1
  • This was my issue facepalm 🤦‍♂️ I forgot to send the value instead i was sending the whole element to my ajax function Oct 8, 2022 at 17:54
2

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

2

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

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

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

1

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

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.

2
  • Where did you add the click()
    – Tcmxc
    Oct 4, 2017 at 17:50
  • 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
    – CodeToLife
    Sep 24, 2021 at 17:54
1

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

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' },
    ]
  }
];
1
  • Yep. I got it solved with this one. I had a recursion in the Angular 11 routes Apr 2, 2021 at 23:43
1

I got this error in express/nodejs app, when the schema of MongoDB database and the models which we have created don't match.

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

0

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.

1
  • Sometimes however, it can be hard to figure out where the error originated. We have a LOT of JavaScript on our site. Apr 16, 2015 at 13:47
0

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

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

0

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.

0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.