| getTimer( ) Global Function | Flash 4 |
| determine how long the Player has been running, in milliseconds |
The number of milliseconds that have elapsed since the Player started running.
The getTimer( ) function indicates how long the Player has been running, in milliseconds. The getTimer( ) function returns a single value, per Player instance, for all movies in the Player. Loading a new .swf does not reset the timer. Prior to Flash 6, developers used multiple calls to getTimer( ) to govern the timed execution of a block of code, or to add time-based features to a movie, such as a countdown in a video game. As of Flash 6, timed code execution should be implemented using setInterval( ).
The following code shows a countdown timer function, doCountdown( ), that displays the seconds remaining on screen. For a more sophisticated CountDown class that uses setInterval( ), see Function.apply( ).
function doCountdown (countAmount) {
// Record the starting time, in milliseconds
var startTime = getTimer();
// Initialize a variable to keep track of how much time has passed
var elapsed = 0;
// Create a text field to display the countdown time in seconds
this.createTextField("counterOutput_txt", 1, 0, 0, 200, 20);
// With each frame that passes...
this.onEnterFrame = function () {
// ...check how much time has passed
elapsed = getTimer() - startTime;
// If the elapsed time is less than the length of our countdown...
if (elapsed < countAmount * 1000) {
// ...set the text field to show the number of seconds left
this.counterOutput_txt.text = countAmount - Math.floor(elapsed / 1000);
} else {
// ...otherwise, our countdown is done, so tell the user
this.counterOutput_txt.text = "Time's Up!";
// Stop checking the time
delete this.onEnterFrame;
}
}
}
// Usage:
doCountDown(60);
To determine the number of full seconds (rather than milliseconds) that have elapsed during a movie, divide the return value of getTimer( ) by 1000, and trim off the decimal portion with either Math.floor( ), Math.round( ), or Math.ceil( ). For example:
numSeconds = Math.floor(getTimer()/1000);
The following code loops between two frames until a movie has been playing for more than 10 seconds, after which it breaks out of the timeline loop:
now = getTimer();
if (now > 10000) {
play();
} else {
gotoAndPlay(_currentframe - 1);
}
The following code does the same thing using setInterval( ):
stop();
intID = setInterval(function () { play(); clearInterval(intID); }, 1000);
clearInterval( ), Date( ), the Date class, setInterval( )