I have the following code sample to illustrate my point. When I load this in IE8 on Vista I get the error "Stack Overfow at line:16"
If I recurse using a top level function (outside of the testClass object) I can recurse millions of times without a stack overflow.
Why is this happening? Ultimately I just implemented a Function Que instead of using recursion, but just doesn't make sense to me, and I'd like to understand the cause.
-- code --
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN">
<html>
<head>
<title>Recusion Test</title>
<body>
</body>
<script type="text/javascript">
function testClass() {
this.x = 15;
this.recurse = function() {
this.x--;
this.recurse();
}
}
var wtf = new testClass();
wtf.recurse();
alert('done');
</script>
</head>
</html>
There is no terminating condition for your recursive statement therefore it will run forever.
It appears that you want...
function testClass() {
this.x = 15;
this.recurse = function() {
if (this.x--)
this.recurse();
}
}
var wtf = new testClass();
wtf.recurse();
alert('done');