在AS3中创建(正确的)时间计数器

Mik*_*ike 6 timer actionscript-3

你如何在as3中创建一个时间计数器?谷歌上的一些简单搜索将指向AS3类定时器,它实际上是一个事件的计数器,而不是一个适当的时间计数实用程序.

我已经看到了这个http://blogs.adobe.com/pdehaan/2006/07/using_the_timer_class_in_actio.html,我有点担心它应该是官方文档.

问:问题究竟在哪里?

答: Timer类在一堆事件中执行操作,如果你有一个非常繁重的应用程序,我可以打赌,如果你用它计算秒,毫秒或其他什么,计时器会扭曲你的时间.

Jos*_*nig 6

如果您希望精确测量较短的时间间隔,只需使用getTimer()函数(flash.utils.getTimer),该函数返回自Flash播放器启动以来经过的毫秒数.典型的简单StopWatch类是:

public class StopWatch {
    private var _mark:int;
    private var _started:Boolean = false;

    public function start():void { _
        mark = getTimer(); 
        _started = true;
    }

    public function get elapsed():int { 
        return _started ? getTimer() - _mark : 0; 
    }
}
Run Code Online (Sandbox Code Playgroud)

更多信息:


Mik*_*ike 2

你如何覆盖这个?

我们只需在脚本中使用Date类即可正确计算时间。

  1. 创建一个新的AS3文档
  2. 添加 3 个名为 minText、secText、MilText 的文本框和一个名为 start_btn 的按钮
  3. 在第一帧添加此代码:

var stt:int;// 我们使用这个变量来跟踪开始时间作为时间戳
var myTimer:Timer = new Timer(1); // 这是我们的计时器

var starttime:Date; // pretty obvious
var actualtime:Date; // pretty obvious

myTimer.addEventListener(TimerEvent.TIMER, stopWatch); // we start counting with this counter

start_btn.addEventListener(MouseEvent.CLICK, startClock); // add a button listener to start the timer

function startClock(event:MouseEvent):void
{
    starttime = new Date(); // we get the moment of start
    stt = int(starttime.valueOf().toString()); // convert this into a timestamp
    myTimer.start(); // start the timer (actually counter)
}

function stopWatch(event:TimerEvent):void
{
    actualtime = new Date(); // we get this particular moment       
    var att:int = int(actualtime.valueOf().toString()); // we convert it to a timestamp

    // here is the magic
    var sec:int = (Math.floor((att-stt)/1000)%100)%60; // we compute an absolute difference in seconds
    var min:int = (Math.floor((att-stt)/1000)/60)%10; // we compute an absolute difference in minutes
    var ms:int = (att-stt)%1000; // we compute an absolute difference in milliseconds

    //we share the result on the screen
    minText.text = String(min);
    secText.text = String(sec);
    milText.text = String(ms);
}
Run Code Online (Sandbox Code Playgroud)

为什么需要时间戳而不使用Date类的函数?

因为如果你想计算两个事件之间的差异,你可能会使用这个:

     endEvent.seconds - startEvent.seconds
Run Code Online (Sandbox Code Playgroud)

如果你的开始事件发生在第 57 秒,结束事件发生在第 17 秒,这是非常错误的,你会得到 -40 秒而不是 20 秒,依此类推。