« インスタンスのメソッドを実行する | メイン | イベントリスナーへの登録 »

一定時間を待つ

インターバルは一定時間間隔で繰り返しの処理を行いたいときに威力を発揮する機能ですが、一定時間を待つタイマーとしても利用できます。
次のサンプルを実行すると5秒後にインターバルで設定したtimeoutイベントが発生するので、そこでインターバルの設定をクリアします。

sample→timer1.fla


フレームアクション:
//timerObjオブジェクトの設定
timerObj = new Object();
timerObj.timeout = function() {
clearInterval(timerID); // インターバルの終了
trace("タイムアウト"); // 出力→ タイムアウト
};
//計測開始(5秒でタイムアウト)
var timerID = setInterval(timerObj, "timeout", 5000);


次のサンプルでは、ステージをクリックした時点から1秒間隔でカウントダウンを行います。カウントダウンの秒数はダイナミックテキストmsgFldに表示しています。
例に示すように10秒のカウントダウンを行いたいならばmyObj.startTimer(10)のように10を引数にしてstartTimer()メソッドを実行します。インターバルは1秒間隔でtimestepイベントを実行するので、10回カウントしたならば10秒経過になるので、そこでインターバルをクリアします。

sample→timer2.fla


フレームアクション:
msgFld.text = "ステージをクリックするとカウントダウンを開始します"
myObj = new Object();
myObj.startTimer = function(sec:Number) {
this.cntdowntimer = sec;
this.timerID = setInterval(this, "timestep", 1000);// インターバルの設定
msgFld.text = this.cntdowntimer + "秒";
};
myObj.timestep = function() {
if (this.cntdowntimer > 1) {
--this.cntdowntimer;//カウントダウン
msgFld.text = this.cntdowntimer + "秒";//表示
} else {
clearInterval(this.timerID);// インターバルのクリア
msgFld.text = "タイムアウトしました";
}
};
//10秒間のカウントダウンスタート
this.onMouseDown = function() {
myObj.startTimer(10);
};

投稿者 oshige : 2005年02月19日 11:52

トラックバック

このエントリーのトラックバックURL:
http://oshige.com/mt/mt-tb.cgi/1178

コメント

コメントしてください




保存しますか?