Timers in ActionScript

import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.Event;

public class Timers {
    public function Timers() {
        // Timers represent a single event in the future. You
        // tell the timer how long you want to wait, and it
        // dispatches an event when that time has elapsed.
        // This timer will wait 2 seconds.
        var timer1:Timer = new Timer(2000, 1);
        timer1.addEventListener(TimerEvent.TIMER, onTimer1);
        timer1.start();

        // If you just wanted to wait, you could have used
        // a delay. One reason a timer may be useful is
        // that you can cancel the timer before it fires.
        // Here's an example of that.
        var timer2:Timer = new Timer(1000, 1);
        timer2.addEventListener(TimerEvent.TIMER, onTimer2);
        timer2.start();

        if (timer2.running) {
            timer2.stop();
            trace("Timer 2 stopped");
        }

        // Give the timer2 enough time to fire, if it ever
        // was going to, to show it is in fact stopped.
        var delayTimer:Timer = new Timer(2000, 1);
        delayTimer.addEventListener(TimerEvent.TIMER, onDelayTimer);
        delayTimer.start();
    }

    private function onTimer1(event:TimerEvent):void {
        trace("Timer 1 fired");
    }

    private function onTimer2(event:TimerEvent):void {
        trace("Timer 2 fired");
    }

    private function onDelayTimer(event:TimerEvent):void {
        // This is where the program would end in a real application
    }
}

This ActionScript code demonstrates the use of timers, which are similar to the timers in the original example. Here’s a breakdown of the changes and explanations:

  1. We use the flash.utils.Timer class to create timers in ActionScript.

  2. Instead of channels, ActionScript uses event listeners to handle timer completion.

  3. The time.Sleep function is replaced with another timer (delayTimer) to simulate the delay at the end of the program.

  4. We use trace() instead of fmt.Println() for console output in ActionScript.

  5. The concept of goroutines doesn’t exist in ActionScript, so we’ve simplified the structure to use event listeners instead.

To run this program, you would typically embed it in a Flash project or compile it with the ActionScript compiler. The output would be similar to:

Timer 2 stopped
Timer 1 fired

Note that Timer 2 is stopped before it has a chance to fire, demonstrating how to cancel a timer before it completes.

ActionScript’s timer system provides a way to schedule code execution in the future or repeatedly at intervals, similar to the timer functionality in other languages.