Hi, I'm Gregor, welcome to my blog where I mostly write about data visualization, cartography, colors, data journalism and some of my open source software projects.

Helper Class For Delayed Code Execution In AS3


This is a small class that I use very often. Its purpose is to simplify the execution of methods after a specific delay. Normally you would have to create a new Timer instance, attach an event listener for the TimerEvent.TIMER event and find a way to store the arguments that you want to pass to the event handler. Using the DelayedExecution class, this whole process goes in one line of code:

function helloWorld(name: String, message: String): void {
	trace(name + ' says "' + message + '"');

new DelayedExecution(4000, this, helloWorld, 'john', 'hello world');
// will result in a 'john says "hello world"' trace after 4 seconds

That’s all. First parameter is the delay in milliseconds, second is the object on which you want to call the method, third is the method itself and any following parameters will be passed to the method. Here you can grep the source of the DelayedExecution class. Feel free to use it for whatever you like.

package net.vis4.utils
	import flash.utils.Timer;

	public class DelayedExecution
		private var
			*  new DelayedExecution(100, Math, round, 4.5);
			*  parameters:
			*  - delay
			*  - object
			*  - function
			*  - parameters
		public function DelayedExecution(... arguments)
			if (arguments.length < 3) {
				trace('DelayedExecution-Error: missing arguments');
			} else {
				if (arguments[0] is uint || arguments[0] is Number) {
					if (arguments[1] is Object) {
						if (arguments[2] is Function) {
							_obj = arguments[1];
							_func = arguments[2];
							_args = [];
							if (arguments.length > 3) {
								for (var i:uint = 3; i < arguments.length; i++) {
							var t:Timer = new Timer(arguments[0] as Number, 1);
							t.addEventListener(TimerEvent.TIMER, exec);
						} else trace('DelayedExecution-Error: third argument should be a function');
					} else trace('DelayedExecution-Error: seconds argument should be an object (this-context of function)');
				} else trace('DelayedExecution-Error: first argument should be a number (milliseconds delay)');

		private function exec(e:Event = null):void
			_func.apply(_obj, _args);