I want to test for large call stacks. Specifically, I want a console warning when the call stack length reaches 1000. This usually means I did something stupid, and can lead to subtle bugs.
Can I compute the call stack length within JavaScript?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Here’s a function that will work in all major browsers, although it won’t work in ECMAScript 5 strict mode because
arguments.calleeandcallerhave been removed in strict mode.Example:
UPDATE 1 November 2011
In ES5 strict mode, there is simply no way to navigate the call stack. The only option left is to parse the string returned by
new Error().stack, which is non-standard, not universally supported and obviously problematic, and even this may not be possible for ever.UPDATE 13 August 2013
This method is also limited by the fact that a function that is called more than once in a single call stack (e.g. via recursion) will throw
getCallStackSize()into an infinite loop (as pointed out by @Randomblue in the comments). An improved version ofgetCallStackSize()is below: it keeps track of functions it has seen before to avoid going into an infinite loop. However, the returned value is the number of different function objects in the callstack before encountering a repeat rather than the true size of the complete call stack. This is the best you can do, unfortunately.