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.
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.
function stackDepth() {
var c=stackDepth.caller, depth=0;
while (c) { c = c.caller; depth++; }
return depth;
}
Chrome seems to think that the stack depth from the console is already 3, so maybe for each JavaScript environment you'd need to determine an initial baseline depth and subtract from that.
stackDepth(); // => 3
(function(){return stackDepth();})(); // => 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With