Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculate elapsed time in flash

Tags:

time

elapsed

I am building a quiz and i need to calculate the total time taken to do the quiz. and i need to display the time taken in HH::MM::SS..any pointers?

like image 857
hitek Avatar asked Nov 18 '25 21:11

hitek


2 Answers

new Date().time returns the time in milliseconds.

var nStart:Number = new Date().time;

// Some time passes

var nMillisElapsed:Number = new Date().time - nStart;

var strTime:String = Math.floor(nMillisElapsed / (1000 * 60 * 60)) + "::" + 
   (Math.floor(nMillisElapsed / (1000 * 60)) % 60) + "::" + 
   (Math.floor(nMillisElapsed / (1000)) % 60);
like image 166
Brian Avatar answered Nov 21 '25 00:11

Brian


I resurrect this question to say that both Brian and mica are wrong. Creating a new Date() gives you the time according to the computer's clock. All someone has to do is set their clock back several minutes, and that would cause the quiz timer to go back several minutes as well. Or worse, they could set their clock back to a time before they started the quiz, and your app would think they spent a negative amount of time taking the quiz. o.O

The solution is to use flash.utils.getTimer(). It returns the number of milliseconds since the swf started playing, regardless of what the computer's clock says.

Here's an example:

var startTime:Number = getTimer();

// then after some time passes:

var elapsedMilliseconds:Number = getTimer() - startTime;

Then you can use Brian's code to format the time for display:

var strTime:String = Math.floor(elapsedMilliseconds / (1000 * 60 * 60)) + "::" + 
(Math.floor(elapsedMilliseconds / (1000 * 60)) % 60) + "::" + 
(Math.floor(elapsedMilliseconds / (1000)) % 60);
like image 21
Jonathan Graef Avatar answered Nov 21 '25 02:11

Jonathan Graef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!