31Jan
[AS 3] Timing Methods with Timer and setInterval
2 comments so farI have been wondering how the setInterval method was integrated in to Actionscript 3 so I wrote up a little application to demonstrate a persistent timer. The movie was just made to trigger a function every 2 seconds
Here is my document class for this movie:
package
{
import flash.display.Sprite;
import flash.utils.setInterval;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFieldType;
import flash.text.TextFormat;
public class SetInterval extends Sprite {
public var timedProcess:uint;
private var output:TextField;
private var ct:uint;
private var ms:Number = 2000;
public function SetInterval()
{
buildFields();
var timedProcess:uint = setInterval(callFunction, ms);
}
private function callFunction():void
{
ct++;
output.text = "timer - " + ct + " (called every " + ms/1000 + " seconds)";
}
private function buildFields():void
{
// Text Formatting
var myTextFormat:TextFormat = new TextFormat();
myTextFormat.font = "Arial";
myTextFormat.color = 0xffffff;
myTextFormat.size = 12;
myTextFormat.align ="center";
myTextFormat.underline = false;
// output TextField
output = new TextField();
output.defaultTextFormat = myTextFormat;
addChild(output);
output.width = 400;
output.height = 250;
output.x = stage.stageWidth / 2 - output.width / 2;
output.y = 35;
}
}
}
If you are looking for a timing method that is performed for a specific number of events then the Timer() method will work great. This will just trigger an event 2 times every second. Here is the document class code for this:
package {
// pulled from: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/utils/Timer.html
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.display.Sprite;
public class TimerExample extends Sprite {
public function TimerExample() {
var myTimer:Timer = new Timer(1000, 2);
myTimer.addEventListener("timer", timerHandler);
myTimer.start();
}
public function timerHandler(event:TimerEvent):void {
trace("timerHandler: " + event);
}
}
}
Categories: Actionscript 3, Timer Methods
Thursday, January 31st, 2008 at 11:17 am and is filed under Actionscript 3, Timer Methods. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Does Timer cause as much lag as setInterval?
I am not really sure about the performance variances among the classes. I do know that Timer class is just Actionscript 3.0’s version of a combination of the setInterval and setTimeout methods. I can only imagine that since the newest version of the flash player is much more efficient than previous versions, that any lag endured in the past may run efficiently with this new method.