Browse the notebook

Tag: recursion

Recursive Tree

var branches:int = 0;
var maxBranches:int = 400;
 
graphics.lineStyle(0,0x000000);

makeBranch(300,350,100,-45,45);
	 
function makeBranch(xp:Number, yp:Number, leng:Number, min:Number, max:Number):void {

	var endX:Number, endY:Number;
	var theta:Number = (min + Math.random()*(max-min) - 90) * Math.PI / 180;
	 
	endX = xp + leng * Math.cos(theta);
	endY = yp + leng * Math.sin(theta);

	graphics.moveTo(xp, yp);
	graphics.lineTo(endX, endY);
	
	if (branches < maxBranches) {
		var newLength:Number = leng*.7; 
		setTimeout(makeBranch, 0, endX, endY, newLength, -90, 0);
		setTimeout(makeBranch, 0, endX, endY, newLength, 0, 90);
	}
	branches+=2;
}

Draws a tree using recursion.

Read snippet: Recursive Tree

Recursion Trick w/ setTimeout()

var counter:int = 0;

graphics.lineStyle(0,0x000000);

recursive();

function recursive():void{
	
	if (counter < 4000){
	   graphics.moveTo(10,10);
	   graphics.lineTo(counter, 200);
	   counter+=4;
          // don't call recursive(), use setTimeout instead
	   setTimeout(recursive,0);
	}else{
		trace(counter / 4 + " lines were drawn");
	}

Be careful with this one, if you don’t know what your doing you may be able to crash flash.

Anyway… if you use a recursive function in flash you may find yourself getting a stack overflow error. You can avoid this by using setTimeout():

 // don't call recursive(), use setTimeout() instead
setTimeout(recursive,0);

Of course… the stack overflow error is there for a reason, if used incorrectly you could bring the flash player to a standstill.

You can also achieve animated recursion by actually adding a delay to your setTimout() call:

 // don't call recursive(), use setTimeout() instead
setTimeout(recursive,10);
Read snippet: Recursion Trick w/ setTimeout()