Search code examples
javascriptstackstack-overflow

determine stack depth in javascript using javascript


Is there a way to determine the stack depth of all functions being executed in javascript by using javascript itself?

I'm thinking it might involve modifying the Function prototype, but I really don't have any idea.

Additionally, it would be nice to be able to break anytime the stack depth were sufficiently high.

The reason for this is that I have a stack overflow error in IE which is apparently not debuggable. I'm lazy and I would rather not have to hunt through the code that I'm maintaining to find the cause.

Thanks for assisting my laziness.


Solution

  • ECMAscript supported for quite a while the Function.prototype.caller property. Even if its deprecated in ES5 strict, IE should still support it. So you could basically loop your way up through the involved functions.

    function one() {
       two();
    }
    
    function two() {
       three();
    }
    
    function three() {
        var caller = three.caller;
    
        console.log('caller was: ', caller.name);
    
        while( caller = caller.caller ) {
               console.log('caller was: ', caller.name);
        }
    }
    
    (function outer() {
        one();
    }());
    

    That will output:

    caller was: two
    caller was: one
    caller was: _outer
    

    So, if you know in which function an error happens, that way you get the answer all the way up how this method was originally called. If you're just after the depth, you can just count how many interations over the caller.caller property were made. At least IE8 should support the "debugger" statement, which you could just call in that script to bring the debugger on the stage.