2012-12-11 416 views
1

我一直在尋找一個示例代碼來創建一個簡單的倒數計時器。AS3帶鬧鐘的簡易計時器?

這將顯示時間在「小時:分鐘:秒」和我必須的時間設定爲10分鐘,30分鐘,1小時,2小時等

當定時器命中的能力零,它會做一個功能。非常感謝您的幫助。我能在網上找到的唯一東西是倒數到特定的日期。

回答

1

製作計時器非常簡單。您可以閱讀更多關於AS3 Timer類的內容。將時間顯示爲HH:MM:SS有點用處。我用這個上課的時候,我需要做的是:

package com.dop.utils 
{ 
    public class Timecodes 
    { 
     public function Timecodes() 
     { 
     } 

     public static function timecodeToSeconds(tcStr:String):Number 
     { 
      var t:Array = tcStr.split(":"); 
      return (t[0] * 3600 + t[1] * 60 + t[2] * 1); 
     } 

     public static function secondsToTimecode(seconds:Number):String 
     { 
      var minutes:Number   = Math.floor(seconds/60); 
      var remainingSec:Number  = seconds % 60; 
      var remainingMinutes:Number = minutes % 60; 
      var hours:Number   = Math.floor(minutes/60); 
      var floatSeconds:Number  = Math.floor((remainingSec - Math.floor(remainingSec))*100); 
      remainingSec    = Math.floor(remainingSec); 

      return getTwoDigits(hours) + ":" + getTwoDigits(remainingMinutes) + ":" + getTwoDigits(remainingSec); 
     } 

     private static function getTwoDigits(number:Number):String 
     { 
      if (number < 10) 
      { 
       return "0" + number; 
      } 
      else 
      { 
       return number + ""; 
      } 
     } 
    } 
} 

我做了一個小例子,你可以使用這個類在這裏看到:http://ronnieswietek.com/cc/alarm/alarm.swf

(和源在這裏:http://ronnieswietek.com/cc/alarm/alarm.fla

代碼我用的是利用Timer類是在這裏:

import com.dop.utils.Timecodes; 
import flash.events.*; 
import fl.controls.*; 
import fl.data.*; 
import flash.utils.Timer; 

var timer:Timer = new Timer(1000); //-- run once a second 
timer.addEventListener(TimerEvent.TIMER, onTimer); 

var countdown:Number = 0; 
var durations:Array = [ 
    {label:'1 minute',time:1}, 
    {label:'5 minutes',time:5}, 
    {label:'10 minutes',time:10}, 
    {label:'30 minutes',time:30}, 
    {label:'1 hour',time:60}, 
    {label:'2 hours',time:120}, 
    {label:'3 hours',time:180} 
]; 

durationBox.dataProvider = new DataProvider(durations); 
timerButton.addEventListener(MouseEvent.CLICK, timerHandler); 

function timerHandler(e:MouseEvent):void 
{ 
    if (!timer.running) 
    { 
     var selectedTime:Number = durationBox.selectedItem.time * 60; 
     countdown = selectedTime; 
     timeText.text = Timecodes.secondsToTimecode(countdown); 
     timer.start(); 
     timerButton.label = "Stop"; 
    } 
    else 
    { 
     countdown = 0; 
     timeText.text = Timecodes.secondsToTimecode(countdown); 
     timer.stop(); 
     timer.reset(); 
     timerButton.label = "Start"; 
    } 
} 

function onTimer(e:TimerEvent):void 
{ 
    timeText.text = Timecodes.secondsToTimecode(countdown); 
    countdown--; 
    if (countdown == 0) 
    { 
     timer.stop(); 
     timer.reset(); 
     timeText.text = "ALARM!!!"; 
    } 
} 
+0

哇。謝謝!我期待着您的資源! – akhunaton

+0

再次感謝。你的解決方案工作得很好。 – akhunaton

+0

真棒,很高興幫助你 – Ronnie

1

在要求的精度,你不能依靠Timer類ALO ne給你一段精確的時間。特別是如果Flash Player正在做很多其他工作。這是因爲Timer類間隔實際上是一個請求而不是保證。讓我們一起來看看,開始用一個簡單的實施計時器的滴答1次(1000毫秒):

private var startTime:uint; 
private var ticks:int; 

protected function start():void 
{ 
    var t:Timer = new Timer(1000); 
    t.addEventListener(TimerEvent.TIMER, timerTick); 
    t.start(); 
    startTime = getTimer(); 
} 

protected function timerTick(event:TimerEvent):void 
{ 
    trace('Ideal: ' + (++ticks) + ' Actual: ' + (getTimer()-startTime)/1000); 
} 

使用getTimerget familiar with getTimer)來衡量的實際時間,我們可以在20秒內看到Timer類是半秒鐘之後。這種漂移將在每次這個運行時間變化:

Expected: 1 Actual: 1.043 
Expected: 2 Actual: 2.083 
Expected: 3 Actual: 3.082 
… 
Expected: 18 Actual: 18.417 
Expected: 19 Actual: 19.457 
Expected: 20 Actual: 20.5 

這就是實現一個秒錶就派上用場了測量時間更精確:

import flash.utils.getTimer; 

public class Stopwatch 
{ 
    private var startStamp:Number; 
    private var stopStamp:Number; 
    private var runTime:Number; 

    private var _countdownDuration:Number; 

    private var started:Boolean; 
    private var stopped:Boolean; 
    private var paused:Boolean; 

    function Stopwatch(startNow:Boolean = true):void 
    { 
     if (startNow) 
      start(); 
    } 

    public function start():void 
    { 
     runTime = 0; 
     startStamp = getTimer(); 
     _countdownDuration = 0; 
     started = true; 
     stopped = false; 
     paused = false; 
    } 

    public function startCountdown(milliseconds:Number):void 
    { 
     start(); 
     _countdownDuration = milliseconds; 
    } 

    public function pause():void 
    { 
     if (started && ! stopped) 
     { 
      runTime += getTimer() - startStamp; 
      paused = true; 
     } 
    } 

    public function resume():void 
    { 
     if (started && paused) 
     { 
      startStamp = getTimer(); 
      paused = false; 
     } 
    } 

    public function stop():void 
    { 
     if (started && ! stopped) 
     { 
      if (! paused) 
       runTime += getTimer() - startStamp; 

      stopped = true; 
      paused = false; 
     } 
    } 

    public function set elapsed(value:uint):void 
    { 
     runTime = value; 

     if (running) 
      startStamp = getTimer(); 
    } 

    public function get elapsed():uint 
    { 
     if (running) 
      return (getTimer() - startStamp) + runTime; 

     return runTime; 
    } 

    public function get running():Boolean 
    { 
     return (started && ! paused && ! stopped); 
    } 

    public function get countdownDuration():Number 
    { 
     return _countdownDuration; 
    } 

    public function set countdownDuration(value:Number):void 
    { 
     _countdownDuration = value; 
    } 

    public function get remaining():int 
    { 
     if (! _countdownDuration) 
      return 0; 
     else if (_countdownDuration - elapsed < 0) 
      return 0; 

     return _countdownDuration - elapsed; 
    } 
} 

擴展用秒錶可以有效地測量通道的第一個例子時間很簡單(只記得stopwatch.elapsed以毫秒爲單位,所以我們將通過1000秒分):

private var stopwatch:Stopwatch; 

protected function start():void 
{ 
    var t:Timer = new Timer(1000); 
    t.addEventListener(TimerEvent.TIMER, timerTick); 
    t.start(); 
    stopwatch = new Stopwatch; 
    stopwatch.start(); 
} 

protected function timerTick(event:TimerEvent):void 
{ 
    trace(stopwatch.elapsed/1000 + ' seconds have elapsed', 
      (60 * 10) - stopwatch.elapsed/1000 + ' seconds remain'); 
} 

由於stopwatch.elapsed以毫秒爲單位,您需要將該數量轉換爲不同的時間增量。繼單一職責原則,我們會讓稱爲StopwatchFormatter一個可重用的通用類來幫助我們鞏固這些計算和揭露可讀API:使用這兩個類,我們有一個簡單的計時器一起

public class StopwatchFormatter 
{ 
    private var elapsed:Number; 
    public var paddedSize:int; 
    public var cappedDecimalLength:int; 

    function StopwatchFormatter(paddedSize:Number = 2, cappedDecimalLength:Number = 1, elapsed:Number = 0) 
    { 
     this.elapsed = elapsed; 
     this.paddedSize = paddedSize; 
     this.cappedDecimalLength = cappedDecimalLength; 
    } 

    // INPUTS 

    public function setTimeAsGroup(hours:Number, minutes:Number = 0, seconds:Number = 0, milliseconds:Number = 0):StopwatchFormatter 
    { 
     elapsed = (hours * 60 * 60 * 1000) + (minutes * 60 * 1000) + (seconds * 1000) + milliseconds; 

     return this; 
    } 

    public function set totalMilliseconds(value:Number):void 
    { 
     elapsed = value; 
    } 

    public function set totalSeconds(value:Number):void 
    { 
     elapsed = value * 1000; 
    } 

    public function set totalMinutes(value:Number):void 
    { 
     elapsed = value * 1000 * 60; 
    } 

    public function set totalHours(value:Number):void 
    { 
     elapsed = value * 1000 * 60 * 60; 
    } 

    // CLOCK LIKE 
    // (converting to int will drop the decimal place) 

    public function get milliseconds():int 
    { 
     return elapsed % 1000; 
    } 

    public function get seconds():int 
    { 
     return (elapsed/1000) % 60; 
    } 

    public function get minutes():int 
    { 
     return (elapsed/1000/60) % 60; 
    } 

    public function get hours():int 
    { 
     return (elapsed/1000/60/60) % 24; 
    } 

    // CLOCK PADDED (zeroes in the front) 
    // 5 becomes "05" , 10 becomes "10" where _paddedSize is 2 

    public function get millisecondsPadded():String 
    { 
     return frontPad(milliseconds); 
    } 

    public function get secondsPadded():String 
    { 
     return frontPad(seconds); 
    } 

    public function get minutesPadded():String 
    { 
     return frontPad(minutes); 
    } 

    public function get hoursPadded():String 
    { 
     return frontPad(hours); 
    } 

    // TOTAL 

    public function get totalMilliseconds():Number 
    { 
     return elapsed; 
    } 

    public function get totalSeconds():Number 
    { 
     return elapsed/1000; 
    } 

    public function get totalMinutes():Number 
    { 
     return elapsed/1000/60; 
    } 

    public function get totalHours():Number 
    { 
     return elapsed/1000/60/60; 
    } 

    // TOTAL CAPPED 
    // 3.134 becomes 3.1 where _cappedDecimalLength is 1 

    public function get totalMillisecondsCapped():Number 
    { 
     return capped(totalMilliseconds); 
    } 

    public function get totalSecondsCapped():Number 
    { 
     return capped(totalSeconds); 
    } 

    public function get totalMinutesCapped():Number 
    { 
     return capped(totalMinutes); 
    } 

    public function get totalHoursCapped():Number 
    { 
     return capped(totalHours); 
    } 

    // TOTAL CAPPED + PADDED (zeroes in the back and one zero in the front for values less than 0) 
    // 3.101 becomes "3.10" where _cappedDecimalLength is 2 

    public function get totalSecondsCappedPadded():String 
    { 
     return capped(totalSeconds).toFixed(cappedDecimalLength); 
    } 

    public function get totalMinutesCappedPadded():String 
    { 
     return capped(totalMinutes).toFixed(cappedDecimalLength); 
    } 

    public function get totalHoursCappedPadded():String 
    { 
     return capped(totalHours).toFixed(cappedDecimalLength); 
    } 

    // UTILITY FUNCTIONS 

    private function frontPad(n:int):String 
    { 
     var s:String = n.toString(); 
     if (s.length < paddedSize) 
     { 
      var i:int = 0; 
      var len:int = paddedSize - s.length; 
      for (; i < len; i++) 
      { 
       s = "0" + s; 
      } 
     } 
     return s; 
    } 

    private function capped(input:Number):Number 
    { 
     if (cappedDecimalLength == 0) 
      return Math.floor(input); 

     var decimalFactor:Number = Math.pow(10, cappedDecimalLength); 

     return Math.floor(input * decimalFactor)/decimalFactor; 
    } 
} 

拉這一切倒數方式:

private var stopwatch:Stopwatch; 
private var time:StopwatchFormatter; 

protected function start():void 
{ 
    var t:Timer = new Timer(1000); 
    t.addEventListener(TimerEvent.TIMER, timerTick); 
    t.start(); 
    stopwatch = new Stopwatch; 
    stopwatch.startCountdown(new StopwatchFormatter().setTimeAsGroup(1, 10, 30).totalMilliseconds); 
    time = new StopwatchFormatter; 
} 

protected function timerTick(event:TimerEvent):void 
{ 
    time.totalMilliseconds = stopwatch.elapsed; 
    var elapsed:String = time.hoursPadded + ':' + time.minutesPadded + ':' + time.secondsPadded + ':' + time.millisecondsPadded; 

    time.totalMilliseconds = stopwatch.remaining; 
    var remainig:String = time.hoursPadded + ':' + time.minutesPadded + ':' + time.secondsPadded + ':' + time.millisecondsPadded; 

    trace('Elapsed:', elapsed, "Remaining:", remainig); 
}