-1

I am trying to read the amount of functions on the call stack. Is there any possibility to do this with javascript?

Thank you in advance!

edit: As far as I understand, the call stack contains the functions which are excecuted at the moment. For example

foo(){
bar();
}

leads to the call stack

bar
foo

My question is now if it is possible to get the amount of functions (in this case 2)

SevenOfNine
  • 630
  • 1
  • 6
  • 25

1 Answers1

2

The question lacks detail so I assume the following specs: output a count of the number of functions in a stack trace.

First get the stack trace by constructing an error.

function getStack() {
  return new Error().stack;
}

Each call in the stack trace is separated by a new line so we can count them:

function getStackCount() {
  return new Error().stack.split('\n').length;
}

To adjust for the function call here you could minus two (one for the new Error() and one for the getStackCount():

function getStackCount() {
  return Math.max(new Error().stack.split('\n').length - 2, 0);
}
Sukima
  • 9,965
  • 3
  • 46
  • 60