Tag Archives: setTimeout

Recursion Trick w/ setTimeout()

Actionscript:
  1. var counter:int = 0;
  2.  
  3. graphics.lineStyle(0,0x000000);
  4.  
  5. recursive();
  6.  
  7. function recursive():void{
  8.    
  9.     if (counter <4000){
  10.        graphics.moveTo(10,10);
  11.        graphics.lineTo(counter, 200);
  12.        counter+=4;
  13.           // don't call recursive(), use setTimeout instead
  14.        setTimeout(recursive,0);
  15.     }else{
  16.         trace(counter / 4 + " lines were drawn");
  17.     }

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():

Actionscript:
  1. // don't call recursive(), use setTimeout() instead
  2. 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:

Actionscript:
  1. // don't call recursive(), use setTimeout() instead
  2. setTimeout(recursive,10);

Posted in functions | Also tagged , , | Leave a comment