Posted By

scottwatkins on 04/06/11



Versions (?)

Who likes this?

1 person have marked this snippet as a favorite


ActionScript 3 Delay Function

 / Published in: ActionScript 3

I've updated this snippet to remove the timer and null it after the function is repeated repeat times. You use it like this:

delay(functionname, [param1, param2], 350, 3);

This will call functionname three times with a 350 millisecond delay between each call and pass param1 and param2 to the function.

If you need to call a function that doesn't accept parameters, pass an empty array [] to the second argument.

  1. import;
  2. import flash.utils.Timer;
  4. /**
  5.  * delay function
  6.  * a quick and easy delay function that can call a function with parameters. configurable
  7.  * with delay time and repeat frequency
  8.  *
  9.  * @param func:Function The function to call when timer is complete
  10.  * @param params:Array An array of parameters to pass to the function
  11.  * @param delay:int [OPTIONAL] The number of milliseconds to wait before running the function
  12.  * @param repeat:int [OPTIONAL] The number of times the function should repeat
  13.  */
  14. private function delay(func:Function, params:Array, delay:int = 350, repeat:int = 1):void
  15. {
  16. var f:Function;
  17. var timer:Timer = new Timer(delay, repeat);
  18. timer.addEventListener(TimerEvent.TIMER, f = function():void
  19. {
  20. func.apply(null, params);
  21. if (timer.currentCount == repeat)
  22. {
  23. timer.removeEventListener(TimerEvent.TIMER, f);
  24. timer = null;
  25. }
  26. });
  27. timer.start();
  28. }

Report this snippet  


RSS Icon Subscribe to comments
Posted By: scottwatkins on April 6, 2011

Be sure to include the timer classes

import; import flash.utils.Timer;

Posted By: scottwatkins on April 6, 2011

This is a function that I've needed but wasn't available in AS3. Basically, we create a timer, add a listener to it, and start the timer. In the listener, we run the supplied function with the supplied parameters, then remove the listener.

Posted By: scottwatkins on April 6, 2011

UPDATE: I've had to remove the timer = null declaration because that was clearing the timer variable before additional iterations were completed. It worked fine when repeat was set to 1, but when repeat was greater than 1, timer was nulled out before the second iteration could be started.

Posted By: scottwatkins on April 7, 2011

UPDATE: I've fixed the timer = null issue. The function now works as expected.

Posted By: dakshaau on January 31, 2013

This was Exactly what I was looking for ..... thank you very much!! ^_^

You need to login to post a comment.