The problem with your code is that the variables are defined without the var
keyword, so they are defined in the global scope.
In the clickTile function, you should replace
// rowNum is defined in the global scope,
// Its value is overwritten with each recursive call
rowNum = $tile.parent().prevAll('div').length
with
// rowNum has the function as a scope,
// its keeps different rowNum values for each recursive function call
var rowNum = $tile.parent().prevAll('div').length
The rowNum
(and other variables) values are overwritten by recursive calls, so further conditions will behave incorrectly
if (rowNum > 0) { // rowNum can be anything at this point
// The condition is randomly met
}
Add the var
keyword to your variables, and your code should work as expected.
More about javascript scopes here.