1

我尝试过以下代码及其工作,但是当它达到 130 时我该如何停止?

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

my_txt.text = textValue.toString();

function counter(){
    textValue += addValue;
    my_txt.text = textValue.toString();
}

setInterval(counter, 10);
4

3 回答 3

4

setInterval 以 unsigned int ( uint) 形式返回唯一 ID。您可以使用带有此 ID 的 clearInterval 来停止间隔。编码:

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 );
于 2013-03-09T19:50:37.520 回答
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);
于 2013-03-09T19:51:48.920 回答
0

由于您似乎正在使用 actionscript 3,因此我建议您根本不要使用间隔。Timer 对象可能会更好,因为它可以提供更好的控制,例如能够在停止自身之前设置它触发的次数,并且能够根据需要轻松启动、停止和重新启动计时器。

使用 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

于 2013-03-10T01:48:44.077 回答