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)
data
in ajax. Fixed the error by declaring the variables.
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);
You can sometimes get this if you accidentally import/embed the same JavaScript file twice, worth checking in your resources tab of the inspector.
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...
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.
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
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.
var uintArray = new Uint16Array(bytes); var converted = []; uintArray.forEach(function(byte) {converted.push(String.fromCharCode(byte))});
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>
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]);
}
el.append(...divs)
after the loop causes this error if you have enough nodes.
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.
In my case, it was that I have 2 variables with the same name!
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/
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
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.
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}
Sending input elements instead of their values will most likely resolve it like FK mentioned
In my case, two jQuery modals were showing stacked on top of each other. Preventing that solved my problem.
Check if you have a function that calls itself. For example
export default class DateUtils {
static now = (): Date => {
return DateUtils.now()
}
}
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
}
}
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
.
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);
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.
onclick="$obj.click()"
in my HTML. Looks like it loops jquery attachment in some way
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
},
.....
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' },
]
}
];
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.
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.
I had this error because I had two JS Functions with the same name
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.
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);
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.
I was trying to assign a variable, a value, when that variable had not been declared.
Declaring the variable fixed my error.
Success story sharing