How do you stop a setInterval function?
I have a function that I want to run at an interval within a frame. I use the following code to start the function:
var intervalID = setInterval(intervalFun开发者_如何学编程ction, 3000);
Then, in a button's onRelease I want to stop the function. In the onRelease, I make a transition to another frame.
btn.onRelease = function()
{
clearInterval(intervalID);
gotoAndPlay("nextframe");
}
The intervalFunction continues to execute. What am I doing wrong?
Not sure if this solves your problem or not, but if you only need the timer to fire once, you could use setTimeout() instead. The only difference between that and setInterval() is that setInterval() repeats and setTimeout() does not. Here's some examples.
[EDIT] After rereading the question, you can probably disregard that first paragraph, though the examples may still help. [/EDIT]
Addressing your specific question though, it doesn't look like you're doing anything wrong. Might be a silly question, but does intervalID contain the correct value in the debugger when clearInterval is called?
I agree with bhups -- try checking the scope of intervalID. For testing purposes, use an absolute reference to intervalID and see if you get the same behavior.
btn.onRelease = function()
{
clearInterval(root.<<path to proper level>>.intervalID);
gotoAndPlay("nextFrame");
}
If you're using AS 3, you could also try switching to the Timer class.
var timer:Timer = new Timer(3000);
timer.addEventListener(TimerEvent.TIMER, intervalFunction);
timer.start();
btn.addEventListener(MouseEvent.CLICK, btnClick);
function btnClick(evt:MouseEvent):void
{
timer.stop();
timer.removeEventListener(TimerEvent.TIMER, intervalFunction);
gotoAndPlay("nextFrame");
}
(neither of these are tested)
精彩评论