ActionScript 3 Delay Function


/ Published in: ActionScript 3
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. import flash.events.TimerEvent;
  2. import flash.utils.Timer;
  3.  
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.