Mikiku
Mikiku

Reputation: 152

Javascript recursion variable scope

I have a recursive function(see code), if i start with depth 5

When branch

execute(depth-1,x,y,width/2,height/2);

finishes, depth is not 5 for

execute(depth-1,midX,y,width/2,height/2);

but 1, and it produces mess. You can see algorithm here: http://jsfiddle.net/g4p66/

It supposed to produce something that looks like a maze(a poorly designed maze, hah)

    function execute(depth,x,y,width,height){
        if(depth > 0){
            var midX = (x+width)/2;
            var midY = (y+height)/2;
            c.save();
            c.beginPath();
            c.moveTo(midX,midY);
            var from = Math.floor(Math.random()*4);
            if(from === 0){
                c.lineTo(midX,y);
            } else if(from === 1){
                c.lineTo(x+width,midY);
            } else if(from === 2){
                c.lineTo(midX,y+height);
            } else if(from === 3){
                c.lineTo(x,midY);
            }
            c.stroke();
            c.restore();
            execute(depth-1,x,y,width/2,height/2);
            console.log(depth);
            execute(depth-1,midX,y,width/2,height/2);
            execute(depth-1,x,midY,width/2,height/2);
            execute(depth-1,midX,midY,width/2,height/2);
        }
    }

EDIT: I was reading console.log wrongly, so it got me confused. The main reason is my midX midY calculation was wrong, should be:

var midX = (x+(x+width))/2;
var midY = (y+(y+height))/2;

Upvotes: 2

Views: 2368

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382194

You don't have a variable scope problem but a problem of logic in interpreting the log.

The first console.log you see isn't the one at the top level of the recursion but the one at the deepest level, because that's the execution order.

Here's what happens :

execute(5)
   execute(4)
      execute(3)
         execute(2)
            execute(1)
                execute(0) : depth <=0 -> return
            console.log(depth) -> logs 1

You can check on your own screeshot that you're deep in the recursion when you get to the log :

enter image description here

Upvotes: 2

Related Questions