2013-03-09 67 views

回答

4

的setInterval返回一個唯一的ID作爲一個unsigned int(uint)。您可以使用clearInterval和該ID來停止時間間隔。代碼:

var textValue:Number = 67.1; 
var addValue:Number = .1; 
var myInterval:uint; 
function counter(){ 
    textValue += addValue; 
    my_txt.text = textValue.toString(); 
    if(textValue >= 130) { 
     clearInterval(myInterval); 
    } 
} 
myInterval = setInterval(counter, 10); 
+0

打我吧;) – 2013-03-09 19:52:22

+0

嘿,是的,和接近相同的代碼! – Dave 2013-03-09 19:53:25

+0

完美地工作:)謝謝 – 2013-03-09 19:53:54

2

您可以使用clearInterval來停止時間間隔。試試這個:

var textValue:Number = 67.1; 
var addValue:Number = .1; 

my_txt.text = textValue.toString(); 

function counter(){ 
    textValue += addValue; 
    my_txt.text = textValue.toString(); 
    //check for end value 
    if (textValue>=130) 
    { 
     //clear the interval 
     clearInterval(intervalID); 
    } 
} 

//store the interval id for later 
var intervalID:uint = setInterval(counter, 10); 
+0

1084:語法錯誤:在程序結束前期待rightbrace。 – 2013-03-09 19:59:57

+0

..........修正 – 2013-03-10 01:28:02

0

因爲好像你可能使用的是actionscript 3,所以我建議不要使用間隔。 Timer對象可能更好,因爲它可以提供更好的控制,例如可以設置在停止自身之前觸發的次數,並且可以根據需要輕鬆啓動,停止和重新啓動計時器。

使用定時器對象並添加一個事件監聽器用於每個蜱

import flash.utils.Timer; 
import flash.events.TimerEvent; 

// each tick delay is set to 1000ms and it'll repeat 12 times 
var timer:Timer = new Timer(1000, 12); 

function timerTick(inputEvent:TimerEvent):void { 
    trace("timer ticked"); 

    // some timer properties that can be accessed (at any time) 
    trace(timer.delay); // the tick delay, editable during a tick 
    trace(timer.repeatCount); // repeat count, editable during a tick 
    trace(timer.currentCount); // current timer tick count; 
    trace(timer.running); // a boolean to show if it is running or not 
} 
timer.addEventListener(TimerEvent.TIMER, timerTick, false, 0, true); 

控制計時器的

示例:

timer.start(); // start the timer 
timer.stop(); // stop the timer 
timer.reset(); // resets the timer 

兩個事件它拋出:

TimerEvent.TIMER // occurs when one 'tick' of the timer has gone (1000 ms in the example) 
TimerEvent.TIMER_COMPLETE // occurs when all ticks of the timer have gone (when each tick has happened 11 times in the example) 

API文檔:http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/Timer.html

+0

爲什麼值得setTimeout實際上在後臺使用Timer對象http://stackoverflow.com/questions/2683398/timer-vs-settimeout Timer和性能之間的差異setTimeout可以忽略,但重要的是將時間事件合併到儘可能少的計時器對象中 – 2013-03-31 02:23:39

相關問題