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);

Leave a Reply

Your email address will not be published. Required fields are marked *