2

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?

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

I was going through a coding challenge and stuck here. Is there any way to make it run using setTimeout()?
Problem with setTimeout is that it's a macrotask, not a microtask, and iterating through 60k macrotasks will take a while. But I guess you could check the current stack size, and create a new stack only if the old one is too large
2

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

1 Comment

Nice thought! But I just wanted to overcome that error. Thanks for the another way!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.