Reputation: 1638
I tried to run the following code in both Firefox and Chrome, it gets run in Firefox but in Chrome: Maximum call stack size exceeded
.
const list = new Array(60000).join('1.1').split('.');
function removeItemsFromList() {
var item = list.pop();
if (item) {
removeItemsFromList();
}
};
removeItemsFromList();
Is there any way to prevent it and make it run in all the browsers?
Upvotes: 2
Views: 3205
Reputation: 714
You are reaching the max stack size because you are calling removeItem recursively, an alternate solution can be:
function removeItemsFromList() {
while(list.length > 0){
list.pop();
}
};
removeItemsFromList();
Upvotes: 1
Reputation: 370699
One option to avoid the error would be to make the recursive call only after a Promise.resolve
:
const list = new Array(60000).join('1.1').split('.');
function removeItemsFromList() {
var item = list.pop();
if (item) {
return Promise.resolve().then(removeItemsFromList);
}
};
removeItemsFromList()
.then(() => console.log('Done'));
If you want to do it with setTimeout
instead of Promises, put the recursive call in a setTimeout
only if the current stack size is too large:
const list = new Array(60000).join('1.1').split('.');
let i = 0;
function removeItemsFromList() {
i++;
var item = list.pop();
if (!item) {
console.log('Done');
return;
}
if (i > 5000) {
i = 0;
setTimeout(removeItemsFromList);
} else {
removeItemsFromList();
}
};
removeItemsFromList();
Upvotes: 2
Reputation: 17048
What about a non recursive version ?
const list = new Array(60000).join('1.1').split('.');
function removeItemsFromList() {
var item = list.pop();
while (item) {
item = list.pop();
}
};
removeItemsFromList();
Here are some numbers on maximum callstack allowed (source):
Node.js: 11034
Firefox: 50994
Chrome: 10402
Upvotes: 2