Posted By

adrianparr on 03/18/10


Tagged

timer duration as3 milliseconds Stopwatch getTimer formatTime formatNumber secs hrs mins


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

b121417
tspitzr
wreaper


AS3 Formatted Stopwatch Functionality


 / Published in: ActionScript 3
 

This script expects there to be two movieclips on the stage, one with an instance name of 'startTimer' and the other with an instance name of 'stopTimer'. The duration is then traced to the output window.

  1. import flash.utils.getTimer;
  2.  
  3. startTimer.addEventListener(MouseEvent.CLICK, onStartTimer_CLICK);
  4. stopTimer.addEventListener(MouseEvent.CLICK, onStopTimer_CLICK);
  5.  
  6. var startTime:int;
  7. var stopTime:int;
  8.  
  9. function onStartTimer_CLICK(event:MouseEvent):void {
  10. startTime = getTimer();
  11. trace("startTime: "+startTime);
  12. }
  13.  
  14. function onStopTimer_CLICK(event:MouseEvent):void {
  15. stopTime = getTimer();
  16. trace("stopTime: "+stopTime);
  17. var timeDiff:int = stopTime - startTime;
  18. trace("timeDiff: "+timeDiff);
  19. trace(formatTime(timeDiff));
  20. }
  21.  
  22.  
  23. function formatTime($time:uint):String {
  24. var formattedTime:String;
  25. var hrs:uint;
  26. var mins:uint;
  27. var secs:uint;
  28. var ms:uint;
  29.  
  30. var msAfterHrs:uint = $time % ((1000 * 60) * 60);
  31. hrs = ($time - msAfterHrs) / ((1000 * 60) * 60);
  32.  
  33. var msAfterMins:uint = msAfterHrs % (1000 * 60);
  34. mins = (msAfterHrs - msAfterMins) / (1000 * 60);
  35.  
  36. var msAfterSecs:uint = msAfterMins % 1000;
  37. secs = (msAfterMins - msAfterSecs) / 1000;
  38.  
  39. ms = msAfterSecs;
  40.  
  41. if (ms == 100) {
  42. ms = 0;
  43. }
  44.  
  45. //formattedTime = formatNumber(hrs, 2)+":"+formatNumber(mins, 2)+":"+formatNumber(secs, 2)+"."+formatNumber(ms, 3);
  46. formattedTime = formatNumber(hrs, 2)+"h "+formatNumber(mins, 2)+"m "+formatNumber(secs, 2)+"s";
  47.  
  48. return formattedTime;
  49. }
  50.  
  51. function formatNumber($num:uint, $digits:uint):String {
  52. var formattedNum:String;
  53.  
  54. if ($digits == 2) {
  55. if ($num < 10) {
  56. formattedNum = "0"+$num;
  57. } else {
  58. formattedNum = String($num);
  59. }
  60. } else if ($digits == 3) {
  61. if ($num < 10) {
  62. formattedNum = "00"+$num;
  63. } else if ($num < 100) {
  64. formattedNum = "0"+$num;
  65. } else {
  66. formattedNum = String($num);
  67. }
  68. }
  69. return formattedNum;
  70. }

Report this snippet  

You need to login to post a comment.