如何杀死setTimeout()函数

时间:2010-02-03 22:20:40

标签: flash actionscript-3 actionscript

我通过我的应用程序使用setTimeout()函数,但是当它的垃圾收集时间。该方法仍然运行并调用函数。如何阻止它调用某个函数。我尝试将其设置为null但它不起作用

5 个答案:

答案 0 :(得分:16)

setTimeout会返回对超时的引用,您可以在致电clearTimeout时使用该引用。

var myTimeout = setTimeout(...);
clearTimeout(myTimeout);

答案 1 :(得分:2)

请参阅:clearTimeout()

答案 2 :(得分:0)

同上。使用“clearInterval(timeoutInstance)”。

如果您使用的是AS3,我会使用Timer()类

import flash.utils.*;
var myTimer:Timer = new Timer(500);
myTimer.addEventListener("timer", timedFunction);

// Start the timer
myTimer.start();

function timedFunction(e:TimerEvent)
{
  //Stop timer
  e.target.stop();
}

答案 3 :(得分:0)

我有类似的情况,它让我疯了几个小时。我在网上找到的答案也没有帮助,但最终我发现调用System.gc()可以解决问题。

我使用弱引用ENTER_FRAME侦听器来测试实例是否被GC删除。如果GC清除对象,则ENTER_FRAME应该停止运行。

以下是示例:

package {

import flash.display.Sprite;
import flash.events.Event;
import flash.system.System;
import flash.utils.getTimer;
import flash.utils.setTimeout;

public class GCTest {
    private var _sprite:Sprite;

    public function GCTest():void {
        this._sprite = new Sprite();
        this._sprite.addEventListener(Event.ENTER_FRAME, this.test, false, 0, true);
        setTimeout(this.destroy, 1000); //TEST  doesn't work
    }

    private function test(event:Event):void {
        trace("_" + getTimer());    //still in mem
    }

    public function destroy():void {
        trace("DESTROY")
        System.gc();
    }

}}

当您注释掉System.gc();时,即使在调用destroy方法之后,测试方法仍会被调用(因此超时完成)。这可能是因为仍有足够的内存因此GC不会自行启动。 当您注释掉setTimeout时,将不会调用测试方法,这意味着setTimeout肯定是问题所在。

调用System.gc();将停止调度ENTER_FRAME。

我还使用clearTimeout,setInterval和clearInterval进行了一些测试,但这对GC没有影响。

希望这有助于你们中的一些人遇到相同或类似的问题。

答案 4 :(得分:-2)

没关系,clearInterval()!

相关问题