import flash.utils.*;
var intervalId:uint=setInterval(schroedingerCat,1000);
// execute a function once per second and gather interval ID
trace("Cat's been closed in the box.");
function schroedingerCat():void {
if (Math.random()<0.04) {
clearInterval(intervalId); // stop repeating by ID
trace("Cat's dead.");
return;
}
trace("Cat's still alive...");
}
var bombId:uint;
function plantBomb(seconds:Number):uint {
trace("The bomb has been planted, and will blow in "+seconds.toFixed(3)+" seconds!");
var id:uint=setTimeout(boom,seconds*1000); // parameter is in milliseconds
return id;
}
function defuseBomb(id:uint):void {
clearTimeout(id);
trace("Bomb with id",id,"defused!");
}
function boom():void {
trace("BOOM!");
}
setInterval()
is used to perform repeated tasks asynchronously as specified intervals. Internal Timer
object is used, the returned value of type uint
is its internal ID, by which you can access and stop the repeating by calling clearInterval()
. setTimeout()
and clearTimeout()
work similarly, but the call to supplied function is done only once. You can supply additional arguments to both set functions, these will be passed to the function in order. The number of arguments and their type is not checked at compile time, so should you supply a weird combination of arguments, or a function that requires them and receives none, an error "Error #1063: Argument count mismatch" is raised.
You can perform both activities of setInterval
and setTimeout
with regular Timer
objects, by either using 0 or 1 for repeatCount
property, 0 for indefinite repeats, 1 for one.